Home > database >  How to check a given Type is a certain object using reflection?
How to check a given Type is a certain object using reflection?

Time:03-17

Suppose there is the code

sealed trait SomeTrait
case class SomeClass() extends SomeTrait
case object SomeObject extends SomeTrait

And then the someTraitType: Type is obtained via reflection.

To check that someTraitType is the type of SomeClass it can be done easily someTraitType =:= typeOf[SomeClass].

The question is how can someTraitType be checked that is SomeObject?

And a following question, can the SomeObject instance be obtained from having corresponding Type so a simple == can be performed?

CodePudding user response:

You need to be careful when using TypeTag from scala.reflect.runtime.universe._ to check for type equality.

Consider following checks

def isSomeClass[T <: SomeTrait: TypeTag](t: T) = {
  typeOf[T] =:= typeOf[SomeClass]
}

def isSomeObject[T <: SomeTrait: TypeTag](t: T) = {
  typeOf[T] =:= typeOf[SomeObject.type]
}

The above methods seem to work with following setup

val s1 = SomeClass()
val s2 = SomeObject

println(isSomeClass(s1)) //prints true
println(isSomeObject(s2)) //prints true

However the checks fail when compiler "forgets" types of s1 and s2.

val s1: SomeTrait = SomeClass()
val s2: SomeTrait = SomeObject

println(isSomeClass(s1)) //prints false
println(isSomeObject(s2)) //prints false

The better way is to use s1.isInstanceOf[SomeClass] or s2.isInstanceOf[SomeObject.type] that works in both cases.

  • Related