worldterminator
worldterminator

Reputation: 3066

In scala how to determine whether a class object implements a trait

It is something as the code below. I found isAssignableFrom in Java but it's not in scala.

  trait A

  def isTraitA(c:Class[_]) = {
    // check if c implements A
    // something like 
    // classOf[A].isAssignableFrom(c) 
  }
  
  isTraitA(this.getClass)

Upvotes: 0

Views: 1652

Answers (2)

Seth Tisue
Seth Tisue

Reputation: 30453

The code in your question works just fine:

scala 2.13.4> trait A
trait A

scala 2.13.4> def isTraitA(c:Class[_]) = classOf[A].isAssignableFrom(c)
def isTraitA(c: Class[_]): Boolean

scala 2.13.4> isTraitA(classOf[A])
val res0: Boolean = true

scala 2.13.4> isTraitA(classOf[AnyRef])
val res1: Boolean = false

scala 2.13.4> isTraitA((new AnyRef with A).getClass)
val res2: Boolean = true

What led you to believe it doesn't work?

Upvotes: 1

Mateusz Kubuszok
Mateusz Kubuszok

Reputation: 27535

As comments said you can use Java reflection but this ties you to JVM.

If you wanted to use Scala's reflection you can do something like:

import scala.reflect.runtime.universe._

def isTraitA[B: TypeTag]: Boolean = typeOf[B] <:< typeOf[A]

You could then try in REPL that:

class C
class D extends A

isTraitA[C] // false
isTraitA[D] // true

The difference is that you have to pass implicit TypeTag[B] for your type B all the way through from where it is known (so e.g. add : TypeTag after type parameter every time the type is defined as parameter) and it has to be known at some point (so you cannot simple ask for an instance of TypeTag when you only know a String with a canonical name of the type).

Upvotes: 3

Related Questions