我想有一个方法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
类型类可能是最好的解决方案.
trait FromString[T] {
def apply(s: String): T
}
object FromString {
implicit object IntString extends FromString[Int] {
def apply(s: String) = s.toInt
}
implicit object DoubleString extends FromString[Double] {
def apply(s: String) = s.toDouble
}
implicit object BooleanString extends FromString[Boolean] {
def apply(s: String) = s.toBoolean
}
}
def getInstance[T](dataStr: String)(implicit from: FromString[T]): Option[T] =
Some(from(dataStr))
val a = getInstance[Int]("1")
val b = getInstance[Double]("1.0")
val c = getInstance[Boolean]("true")
Run Code Online (Sandbox Code Playgroud)
这将为有效类型提供编译时检查,getInstance并将返回相应的Option类型.