sdinesh94
sdinesh94

Reputation: 1176

How to set the value of a variable based on the generic type - Scala

I am trying to do something like this :-

Trait Hello[A]
{
  val DBAccessDAO =       A match 
                    {  case classname: Class1  => Class1DAO
                       case classname: Class2  => Class2DAO
                    } 
....

//(use appropriate DBAccessDAO to perform DAO operations

} 

How do I do this in scala? I am not sure how to access 'A' and safely check its type.

Thanks

Upvotes: 1

Views: 630

Answers (3)

Bogdan Vakulenko
Bogdan Vakulenko

Reputation: 3390

You can use TypeTag or something from Shapless library, but in you specific case I would propose to look into type class pattern. Getting type parameters using reflection tricks is almost always not the best solution.

Upvotes: 0

Miguel
Miguel

Reputation: 1211

Due to type erasure, you can't access directly the type of T as you want. The compiler generates a ClassTag type for all your classes so you can bypass the type erasure limitations. You can access the ClassTag implicitly:

import scala.reflect.runtime.universe._

class Hello[A : TypeTag] {
  val DBAccessDAO = typeTag[A] match {
        case tag if tag == typeTag[Class1] => ...
        case tag if tag == typeTag[Class2] => ...
    }
} 

Upvotes: 2

sdinesh94
sdinesh94

Reputation: 1176

Here is a quick example that makes use of TypeTag to look up the class info at compile time

import scala.reflect.runtime.universe.{TypeTag,typeOf}


trait Animal26
{
  val name: String
  val sound: String
}


object Tiger26 extends Animal26{

  override val name = "tiger"
  override val sound = "grrr"
}


trait Person26
{
  val title: String
  val status: String
}


object Employee26 extends Person26{

  val title = "worker"
  val status = "professional"

}


class Stack[A: TypeTag] {

  def getMyClass =
  {
    if (typeOf[A] =:= typeOf[Person26])
    Employee26
    else
     Tiger26
  }


}

object App26 extends App{

  val stack = new Stack[Person26]

  println(stack.getMyClass.toString)

}

Upvotes: 0

Related Questions