tauitdnmd
tauitdnmd

Reputation: 368

Determine Generic Type Paramater in Scala

Currently, I'm working with Scala language and I don't know how to determine the type of generic type. I have a class as following code.

class A[K, V]() {
  def print(): Unit = {
    //Check the real type here
  }
}

What I want to do is:

Upvotes: 1

Views: 72

Answers (2)

Shaido
Shaido

Reputation: 28322

You could use TypeTag[T]. From the documentation:

A TypeTag[T] encapsulates the runtime type representation of some type T.

Example code:

import scala.reflect.runtime.universe._
class A[K: TypeTag, V]() {
  def print(): Unit = typeOf[K] match {
    case i if i =:= typeOf[Int] => println("It is an Integer")
    case _ => println("Something else")
  }
}

Testing the code:

val a = new A[Int, String]
val b = new A[Double, String]
a.print()
b.print()

Printed result:

It is an Integer
Something else

Upvotes: 1

ArunavaS
ArunavaS

Reputation: 207

When you are writing generic classes, you should only focus on doing the common/generic operations on the provided values. However, if you really want to do some sort of type checking you can do that using asInstanceOf method.

You need modify you print method something like below.

def print(k: K) = {
    if (k.isInstanceOf[Int]) println("Int type")
    else if ...
}

Upvotes: 0

Related Questions