Blankman
Blankman

Reputation: 267320

Why is generic parameter not required to be set explicitly?

I am confused how this private function readValue is working:

private def readValue[T](path: String, v: => T): Option[T] = {
  try {
    Option(v)
  } catch {
    case e: ConfigException.Missing => None
    case NonFatal(e)                => throw reportError(path, e.getMessage, Some(e))
  }
}

The parameter v is a function that returns T, and T is set when you call it like:

readValue[String]

But in the following snippet, I see readValue being used with no generic parameter type T explicitly defined:

def getInt(path: String): Option[Int] = readValue(path, underlying.getInt(path))

Why is this not

readValue[Int](path, underlying.getInt(path))

i.e. with the Int set explicitly? How is this supposed to work?

Upvotes: 1

Views: 66

Answers (1)

Eugene Zhulenev
Eugene Zhulenev

Reputation: 9744

Underlying Config object 'underlying: Config' has method getInt with return type Int, and this information provides enough evidence to infer type parameter for readValue, so you don't need to define it explicitly

http://en.wikipedia.org/wiki/Type_inference

http://docs.scala-lang.org/tutorials/tour/local-type-inference.html - example with id function should be helpful

Upvotes: 3

Related Questions