Home > database >  working with class as function parameter in Scala
working with class as function parameter in Scala

Time:12-30

Let's say I have the following function:

def sampleFunc (c : Class[]) : Boolean

It takes a class as parameter. It then checks if a certain element el is of type Class[]. I tried accomplishing that by doing

el.isInstanceOf[Class[]]

But that doesn't work, it always returns false. Does someone see what I'm doing wrong here?

CodePudding user response:

c.isInstance(el)

is the dynamic equivalent of the instanceof operator in Java (i.e. the isInstanceOf method in Scala).

CodePudding user response:

You need to use a type class scala.reflect.ClassTag[T]

import scala.reflect.ClassTag
import scala.reflect.classTag

def sampleFunc[T: ClassTag](el: Any): Boolean = {
  classTag[T].runtimeClass.isInstance(el)
}

or via pattern matching

def sampleFunc[T: ClassTag](el: Any): Boolean = {
  el match {
    case _: T => true
    case _    => false
  }
}

However, el.isInstance[T] is still not supported because of type erasure in java.

Now

println(sampleFunc[String](""))
println(sampleFunc[String](1))

will print true and false respectively.

  • Related