Ste*_* K. 4 types type-systems scala class scala-2.8
我已经包装了一条消息,并希望记录我已经包装的消息.
val any :Any = msg.wrappedMsg
var result :Class[_] = null
Run Code Online (Sandbox Code Playgroud)
我能找到的唯一解决方案是匹配所有内容:
result = any match {
case x:AnyRef => x.getClass
case _:Double => classOf[Double]
case _:Float => classOf[Float]
case _:Long => classOf[Long]
case _:Int => classOf[Int]
case _:Short => classOf[Short]
case _:Byte => classOf[Byte]
case _:Unit => classOf[Unit]
case _:Boolean=> classOf[Boolean]
case _:Char => classOf[Char]
}
Run Code Online (Sandbox Code Playgroud)
我想知道是否有更好的解决方案?以下两种方法不起作用:(
result = any.getClass //error
// type mismatch; found : Any required: ?{val getClass: ?}
// Note: Any is not implicitly converted to AnyRef.
// You can safely pattern match x: AnyRef or cast x.asInstanceOf[AnyRef] to do so.
result = any match {
case x:AnyRef => x.getClass
case x:AnyVal => /*voodoo to get class*/ null // error
}
//type AnyVal cannot be used in a type pattern or isInstanceOf
Run Code Online (Sandbox Code Playgroud)
您可以安全地调用.asInstanceOf[AnyRef]
任何Scala值,这将填充原语:
scala> val as = Seq("a", 1, 1.5, (), false)
as: Seq[Any] = List(, 1, 1.5, (), false)
scala> as map (_.asInstanceOf[AnyRef])
res4: Seq[AnyRef] = List(a, 1, 1.5, (), false)
Run Code Online (Sandbox Code Playgroud)
从那里,你可以打电话getClass
.
scala> as map (_.asInstanceOf[AnyRef].getClass)
res5: Seq[java.lang.Class[_]] = List(class java.lang.String, class java.lang.Int
eger, class java.lang.Double, class scala.runtime.BoxedUnit, class java.lang.Boo
lean)
Run Code Online (Sandbox Code Playgroud)
经过2.8.0.RC6的测试,我不知道这在2.7.7中有效.
2.8中绝对新的是从AnyVal派生的类的伴随对象.它们包含方便box
和unbox
方法:
scala> Int.box(1)
res6: java.lang.Integer = 1
scala> Int.unbox(res6)
res7: Int = 1
Run Code Online (Sandbox Code Playgroud)