定义的空特性测试:
trait Test
用于复合类型的内容:
scala> val a : Int with Test = 10.asInstanceOf[Int with Test]
a: Int with Test = 10
和具有复合类型参数的案例类(如未装箱的标记类型:]
scala> case class Foo(a: Int with Test)
error: type mismatch;
found : Double
required: AnyRef
Note: an implicit exists from scala.Double => java.lang.Double, but
methods inherited from Object are rendered ambiguous. This is to avoid
a blanket implicit which would convert any scala.Double to any AnyRef.
You may wish to use a type ascription: `x: java.lang.Double`.
但是它非常适合:
scala> case class Foo(a: List[Int] with Test)
defined class Foo
并且方法定义没有问题:
scala> def foo(a: Int with Test) = ???
foo: (a: Int with Test)Nothing
Scala版本2.10.3
这是正常的编译器行为吗?
您碰到了Scala统一原语和对象的尝试失败的情况之一。由于Scala中的Int
表示Java基本类型int
,因此它不能混入任何特征。当执行asInstanceOf时,Scala编译器会将Int
自动装箱到java.lang.Integer
:
在scala版本2.13.1中,已解决此问题。