定义的空特性测试:
trait Test复合类型中使用的:
scala> val a : Int with Test = 10.asInstanceOf[Int with Test]
a: Int with Test = 10和带有复合类型参数的case类(类似于未装箱的标记类型):
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)NothingScala版本2.10.3
这是正常的编译器行为吗?
发布于 2014-01-22 14:32:39
您遇到了一种情况,Scala试图统一原语和对象的尝试失败了。因为Scala中的Int表示int原语类型,所以它不能将任何特征混入其中。执行asInstanceOf时,Scala编译器将Int自动装箱到java.lang.Integer中。
scala> val a: Int with Test = 10.asInstanceOf[Int with Test]
a: Int with Test = 10
scala> a.getClass
res1: Class[_ <: Int] = class java.lang.Integer但是,在声明类型时不会发生自动装箱,因此必须手动进行:
scala> case class Foo(x: Integer with Test)
defined class Foo但是,在检查类型之前,编译器类型检查器不会自动装箱:
scala> Foo(a)
<console>:12: error: type mismatch;
found : Int with Test
required: Integer with Test
Foo(a)
^因此,必须将变量声明为Integer with Test。
scala> val a: Integer with Test = 10.asInstanceOf[Integer with Test]
a: Integer with Test = 10
scala> Foo(a)
res3: Foo = Foo(10)或者在调用case类时使用强制转换:
val a : Int with Test = 10.asInstanceOf[Int with Test]
scala> a: Int with Test = 10
scala> Foo(a.asInstanceOf[Integer with Test])
res0: Foo = Foo(10)发布于 2020-04-19 13:22:35
正如@Travis所说,这是一个已知的问题,固定在Scala2.11.7中。
在氨化Repl 2.0.4下运行(Scala2.12.10 java 1.8.0_242)
@case class Foo(a: Int with Test)
a: Int with Test = 10https://stackoverflow.com/questions/20094679
复制相似问题