我想要一个方法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()
}
}
我怎样才能在 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")
这将为编译时检查有效类型getInstance
并将返回适当的Option
type.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)