2013-11-20 17 views
9

boş özellik Testi Tanımlı: Kutusuz Etiketli Tip gibi bileşik tipi parametresi ile (Vaka sınıf arkadaşı nesne üretme hatasıyla

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

ve vaka sınıfında: bileşik tip eskiden ne

trait Test 

):

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`. 

Ama mükemmel için çalışmak olduğunu:

scala> case class Foo(a: List[Int] with Test) 
defined class Foo 

Ve yöntemi tanımıyla hiçbir sorun:

scala> def foo(a: Int with Test) = ??? 
foo: (a: Int with Test)Nothing 

Scala versiyonu 2.10.3

normal derleyici davranış mı?

+7

Bu [bilinen bir sorundur] olduğu (https://issues.scala-lang.org/browse/SI-5183). –

cevap

5

Scala'nın ilkelleri birleştirmeye çalıştığı ve Nesnelerin bozulduğu durumlardan birine çarptınız. Scala'daki Int, Java ilkel türünü int temsil ettiğinden, karıştırılmış herhangi bir özelliğe sahip olamaz. asInstanceOf yaparken, Scala derleyici autoboxes Intjava.lang.Integer bir içine:

scala> case class Foo(x: Integer with Test) 
defined class Foo 

Ama sonra: türlerini bildirirken elle yapmak zorunda

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 

Ancak Autoboxing, olmazolarak değişken bildirmek için

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

Yani olurdu: derleyici tipi denetleyicisi türlerini kontrol etmeden önce aUTOBOX olmaz:

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

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

veya vaka sınıfı çağıran bir döküm kullanın:

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)