John Mullins
John Mullins

Reputation: 1101

How to get a type with parameters inside the base class

Is it possible to get a full type (with type parameters) inside the base class. The following example illustrates issue. See TODO:

import scala.reflect.api.Types

abstract class BaseClass {
  def getType: Type = ???  //TODO how to implement
}

case class Child1[M](model: M) extends BaseClass

case class Child2(p: Int) extends BaseClass

...

val c1 = Child1("Hello")
val c2 = Child2(10)

val xs = List(c1, c2)

xs foreach { e: BaseClass =>
  println(e.getType) 
}

// out:
// com.project.Child1[java.lang.String]
// com.project.Child2
// ...

Upvotes: 0

Views: 92

Answers (2)

talex
talex

Reputation: 20456

I can propose you next solution:

trait BaseClass {
  val realType: Any

  def getType: String = realType.toString()
}

case class Child1[M: TypeTag](model: M) extends BaseClass {
  override val realType = typeTag[Child1[M]]

}

case class Child2(p: Int) extends BaseClass {
  override val realType = typeTag[Child2]
}

It produce not exactly the result you want, but pretty close.

val xs = Seq[BaseClass](Child1[String](""), Child2(1))
xs.foreach { e => println(e.getType) }

give next output

TypeTag[test.Child1[String]]
TypeTag[test.Child2]

Upvotes: 1

Ziyang Liu
Ziyang Liu

Reputation: 810

You can add a type parameter to the base class:

abstract class BaseClass[A: TypeTag] {
  def getType = s"${getClass.getName}[${typeOf[A]}]"
}

case class Child1[M: TypeTag](model: M) extends BaseClass[M]
case class Child2(p: Int) extends BaseClass[Unit]

...

xs foreach {e => println(e.getType)}

Upvotes: 2

Related Questions