Scala:如何获得mixin成分?

Itt*_*ayD 10 scala

scala> import java.util.Properties
import java.util.Properties

scala> trait Foo extends Properties
defined trait Foo

scala> classOf[Foo]
res0: java.lang.Class[Foo] = interface Foo

scala> class FooP extends Foo
defined class FooP

scala> classOf[FooP]
res1: java.lang.Class[FooP] = class FooP

scala> classOf[Properties with Foo]
<console>:7: error: class type required but java.util.Properties with Foo found
       classOf[Properties with Foo]
               ^

scala> new Properties with Foo
res2: java.util.Properties with Foo = {}

scala> res2.getClass
res3: java.lang.Class[_] = class $anon$1
Run Code Online (Sandbox Code Playgroud)

有没有一种方法可以在不创建实例或新类的情况下获取'Properties with Foo'类?

ret*_*nym 7

classOf[X]仅在X对应物理类时才有效.T with U是复合类型,并不对应于类.

您可以使用清单来确定类型的擦除.类型擦除T with UT.

scala> trait T
defined trait T

scala> trait U
defined trait U

scala> manifest[T with U]
res10: Manifest[T with U] = T with U

scala> manifest[T with U].erasure
res11: java.lang.Class[_] = interface T
Run Code Online (Sandbox Code Playgroud)

在这里你可以看到List[Int]List[_]具有相同的擦除:

scala> classOf[List[_]]
res13: java.lang.Class[List[_]] = class scala.collection.immutable.List

scala> classOf[List[Int]]
res14: java.lang.Class[List[Int]] = class scala.collection.immutable.List

scala> classOf[List[Int]] == classOf[List[_]]
res15: Boolean = true
Run Code Online (Sandbox Code Playgroud)

  • `new T with U`声明并实例化一个实现接口`T`和`U`的匿名类. (3认同)