0

I am trying to process something from given type in Scala generics like this:

import scala.reflect.runtime.universe._

implicit private val tag: TypeTag[T] = typeTag[T]
private def getTypeString(implicit tag: TypeTag[T]): String = typeOf[T] match {
  case t if t =:= typeOf[OvalTest] => "tests"
  case t if t =:= typeOf[OvalObject]=> "objects"
  case t if t =:= typeOf[OvalState]=> "states"
  case t if t =:= typeOf[OvalVariable] => "variables"
}

I am getting exception:

Exception in thread "main" java.lang.NullPointerException
    at scala.reflect.api.TypeTags.typeOf(TypeTags.scala:357)
    at scala.reflect.api.TypeTags.typeOf$(TypeTags.scala:357)
    at scala.reflect.api.Universe.typeOf(Universe.scala:73)
    at composer.OvalIndexer$ElementsIndexer.getTypeString(OvalIndexer.scala:142)
    at composer.OvalIndexer$ElementsIndexer.<init>(OvalIndexer.scala:148)
    at composer.OvalIndexer$.createIndex(OvalIndexer.scala:48)
    at Main$.main(Main.scala:11)
    at Main.main(Main.scala)

Null Pointer happens on line private val ovalType = getTypeString.

1 Answer 1

3

Why do you have this line?

implicit private val tag: TypeTag[T] = typeTag[T]

It isn't clear what T is in this scope, but the result will be that tag is null because typeTag[T] sees there is an implicit tag: TypeTag[T] available and returns it. Except it isn't initialized yet so it'll see null. Then if typeOf[T] is used with the same T, it'll get null as its implicit argument resulting in the exception you see.

private val ovalType = getTypeString

Without a type parameter it probably infers getTypeString[Nothing]. Is that what you want?

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.