Ronald
Ronald

Reputation: 187

working with class as function parameter in Scala

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?

Upvotes: 0

Views: 225

Answers (2)

Levi Ramsey
Levi Ramsey

Reputation: 20551

c.isInstance(el)

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

Upvotes: 2

Ivan Stanislavciuc
Ivan Stanislavciuc

Reputation: 7275

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.

Upvotes: 0

Related Questions