为什么不需要显式设置泛型参数?
Why is generic parameter not required to be set explicitly?
我很困惑这个私有函数 readValue
是如何工作的:
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))
}
}
参数v
是returnsT
的函数,调用时设置T
如:
readValue[String]
但是 in the following snippet,我看到 readValue
没有明确定义通用参数类型 T
:
def getInt(path: String): Option[Int] = readValue(path, underlying.getInt(path))
为什么不是这个
readValue[Int](path, underlying.getInt(path))
即Int
明确设置?这应该如何工作?
底层 Config 对象 'underlying: Config' 具有 return 类型 Int 的方法 getInt,此信息提供了足够的证据来推断 readValue 的类型参数,因此您无需显式定义它
http://en.wikipedia.org/wiki/Type_inference
http://docs.scala-lang.org/tutorials/tour/local-type-inference.html - 带 id 函数的例子应该有用
我很困惑这个私有函数 readValue
是如何工作的:
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))
}
}
参数v
是returnsT
的函数,调用时设置T
如:
readValue[String]
但是 in the following snippet,我看到 readValue
没有明确定义通用参数类型 T
:
def getInt(path: String): Option[Int] = readValue(path, underlying.getInt(path))
为什么不是这个
readValue[Int](path, underlying.getInt(path))
即Int
明确设置?这应该如何工作?
底层 Config 对象 'underlying: Config' 具有 return 类型 Int 的方法 getInt,此信息提供了足够的证据来推断 readValue 的类型参数,因此您无需显式定义它
http://en.wikipedia.org/wiki/Type_inference
http://docs.scala-lang.org/tutorials/tour/local-type-inference.html - 带 id 函数的例子应该有用