我正在努力弄清楚如何在scala中存储或传递类型.
我想要实现的是这样的:
abstract class Foo( val theType : type )
object Foo{
case object Foo1 extends Foo(String)
case object Foo2 extends Foo(Long)
}
Run Code Online (Sandbox Code Playgroud)
所以在某些时候我可以这样做:
theFoo match{
case String => "Is a string"
case Long => "Is a long"
}
Run Code Online (Sandbox Code Playgroud)
当获得能够施放它的物体时:
theFoo.asInstanceOf[Foo1.theType]
Run Code Online (Sandbox Code Playgroud)
这可能吗?如果可能,是一个很好的方法吗?我最终想要实现的是为字节流处理编写伪模式.例如,如果我有一个模式,Array(Foo1,Foo1,Foo2,Foo3,Foo1)我可以解析抱怨该模式的字节数组,如果在某些时候我有一个不同的字节流,我可以编写一个新的模式,Array(Foo3, Foo4, Foo5)而不必重新实现解析逻辑.
问候,
按要求编辑
假设我有一个名为Command1的数组[Byte] = A973928CB3883FB123
此字节中的数据固定在位置和长度上.换句话说,我知道1-4位是例如一个小日期,5-9是客户的名字等等.
我想要的是编写一个单独的解析函数,它只作为参数的一个模式,并返回模式中每个参数的实际值.
trait Command{
//This is implemented in every command
val schema : List[Tuple[String,Int,Int,Type]] //Position,Size,DataType
def parse() : List[Tuple[String,Int,Int,Type,Any]] = schema.map(//match using the type)
}
class Command1 extends Command {
override val schema = List[Tuple("theName",0,10,String),Tuple("myType",10,12,MyType),Tuple("theId",13,20,Long)]
val theActualName = parse().find(_._1 == "theName")._5.asInstanceOf[String] //I would like to avoid this cast
}
Run Code Online (Sandbox Code Playgroud)
我希望这能澄清我正在努力做的事情.