我想有一个方法getInstance,它接受一个字符串值并返回一个对象的实例,在方法签名中定义为泛型
def getInstance[T](dataStr: String): Option[T] = {
T match {
case typeOf[String] => Some(dataStr) // if type of T is String
case typeOf[Integer] => Some(dataStr.toInt) // if type of T is Integer
case typeOf[Boolean] => Some(dataStr.toBoolean) // if type of T is Boolean
case _ => throw new NoSuchElementException()
}
}
Run Code Online (Sandbox Code Playgroud)
如何在Scala中编写相同的内容?
Scala版本:2.11
scala ×1