2013-11-20 6 views
9

定義空形質テスト):ケースクラスのコンパニオンオブジェクト生成エラー

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

それは通常のコンパイラの動作ですか?

+7

これは、[既知の問題](https://issues.scala-lang.org/browse/SI-5183です)。 –

答えて

5

Scalaがプリミティブとオブジェクトを統合しようとした場合の1つにぶつかりました。 ScalaのIntはJavaプリミティブタイプintを表しているため、それには何らかの特性が混在することはありません。 asInstanceOfを行う場合、Scalaのコンパイラはjava.lang.IntegerIntをautoboxes:

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 

しかし、コンパイラ型チェッカーは、種類をチェックする前AutoBoxのではないだろう。

scala> Foo(a) 
<console>:12: error: type mismatch; 
found : Int with Test 
required: Integer with Test 
       Foo(a) 
       ^

ですから、としてあなたの変数を宣言する必要があります:

scala> val a: Integer with Test = 10.asInstanceOf[Integer with Test] 
a: Integer with Test = 10 

scala> Foo(a) 
res3: Foo = Foo(10) 

やケースクラスを呼び出すときにキャストを使用します。

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)