Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: How to get class of mixin composition?

Tags:

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

Is there a way of getting class of 'Properties with Foo' without creating an instance or new class?

like image 612
IttayD Avatar asked Jan 31 '10 11:01

IttayD


2 Answers

classOf[X] only works if X corresponds to a physical class. T with U is a compound type, and doesn't correspond to a class.

You can use Manifests to determine the erasure of a type. The type erasure of T with U is T.

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

Here you can see that List[Int] and List[_] have the same erasure:

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
like image 84
retronym Avatar answered Sep 23 '22 00:09

retronym


No it is not possible because "X with Y" is an anonymous definition in your example. This is not the case for "class X extends Z with Y" of course.

like image 40
Joa Ebert Avatar answered Sep 20 '22 00:09

Joa Ebert