Hello!How do I find out in my code if a scala class inherits from a specific trait?ex:val myClass = this.getClassif myClass.hasTrait[MyTrait] // I am looking for such a method
Thanks in advance for the helpSébastien
classOf[MyTrait].isInstance(this)
--
Family photographs are a critical legacy for
ourselves and our descendants. Protect that
legacy with a digital backup and recovery plan.
For more information, follow my blog:
But wait, there's more!
scala> trait Foo
defined trait Foo
scala> trait Bar
defined trait Bar
scala> class Bippy extends Foo with Bar { }
defined class Bippy
scala> def f(x: Any) = x match { case _: Foo with Bar => true ; case _
=> false }
f: (x: Any)Boolean
scala> f(new Foo { })
res0: Boolean = false
scala> f(new Bar { })
res1: Boolean = false
scala> f(new Bar with Foo { })
res2: Boolean = true
scala> f(new Foo with Bar { })
res3: Boolean = true
scala> f(new Bippy)
res4: Boolean = true
How is this feat achieved?
scala> class A { def f(x: Any) = x match { case _: Foo with Bar => true
; case _ => false } }
defined class A
scala> :javap -verbose A
Compiled from "<console>"
[...]
public boolean f(java.lang.Object);
Code:
Stack=1, Locals=3, Args_size=2
0: aload_1
1: astore_2
2: aload_2
// One! One instance check! A Ha Ha!
3: instanceof #8; //class Foo
6: ifeq 20
9: aload_2
// Two! Two instance checks! A Ha Ha!
10: instanceof #10; //class Bar
13: ifeq 20
16: iconst_1
17: goto 21
20: iconst_0
21: ireturn
LineNumberTable:
line 9: 0
> But wait, there's more!
> scala> def f(x: Any) = x match { case _: Foo with Bar => true ; case _ =>
> false }
> f: (x: Any)Boolean
> How is this feat achieved?
>
> scala> class A { def f(x: Any) = x match { case _: Foo with Bar => true ;
> case _ => false } }
> defined class A
>
> scala> :javap -verbose A
> Compiled from "<console>"
> [...]
> public boolean f(java.lang.Object);
> Code:
> Stack=1, Locals=3, Args_size=2
> 0: aload_1
> 1: astore_2
> 2: aload_2
> // One! One instance check! A Ha Ha!
> 3: instanceof #8; //class Foo
> 6: ifeq 20
> 9: aload_2
> // Two! Two instance checks! A Ha Ha!
> 10: instanceof #10; //class Bar
In a case of synchronicity, I happened across that feature scarcely
two hours ago. Somehow I had a good feeling that it was going to work.
Cop that, erasure.
-jason