简体   繁体   中英

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)

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 eg 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).

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM