1

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:

  • If K is Int => Print out It is an Integer
  • If K is Long => Print out It is a Long
  • If K is String => Print out It is a String
1
  • Why create a generic class if you need specific type detail? Commented Nov 6, 2017 at 7:05

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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 ...
}

5 Comments

Pattern matching is the more common/accepted approach. isInstanceOf is discouraged.
@ArunavaS Due to some reasons, there is no way to modify my method to have an instance of K as its param. :
@jwvh, true... pardon my oo mentality :P
@tauitdnmd, if you cannot have type instances, then, how can you just do the type checking? Maybe, I am missing something here, according to me, what you are asking is you have a type class and you need to check the provided type from the type class.. which isn't possible practically
@ArunavaS Yes, I also have my own answer is that I can not do type detail checking without an instance of K. That's why I need to know do we have any solution for this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.