ale*_*ipa 6 generics scala type-inference
我有一个带有getter方法的地图.键始终为String,值为Any.我想允许调用者使用如下方法
get[Int](k: String)
get[Boolean](k:String)
Run Code Online (Sandbox Code Playgroud)
在此方法中,将字符串转换为用户指定的特定类型.我脑海里浮现出的直接解决方案是
def get[T](k: String): T = k.asInstanceOf[T]
Run Code Online (Sandbox Code Playgroud)
这不起作用.然后我尝试了
def cast[T](x: String, classTag: ClassTag[T]): T = classTag match {
case Int => x.toInt
case Boolean => x.toBoolean
...
}
Run Code Online (Sandbox Code Playgroud)
哪个不编译.我不确定这是否可行.任何想法或我需要写出我想要的所有方法?例如
def getInt(k: String): Int
def getBoolean(k: String): Boolean
...
Run Code Online (Sandbox Code Playgroud)
这是scala中广泛使用的类型模式的经典用例.我假设您有自定义的实现Map
和get
方法.
trait Converter[T]{ // typeclass
def convert(t:String):T
}
implicit object ToIntConverter extends Converter[Int] {
def convert(t:String):Int = t.toInt
}
implicit object ToBooleanConverter extends Converter[Boolean] {
def convert(t:String):Boolean = t.toBoolean
}
// vvv approach bellow works starting from scala 2.12 vvv
//
// implicit val ToBooleanConverter: Converter[Boolean] = s => s.toBoolean
// implicit val ToIntConverter : Converter[Int] = s => s.toInt
def get[T](k:String)(implicit cv: Converter[T]):T= cv.convert(k)
println(get[Int]("1"))
println(get[Boolean]("true"))
Run Code Online (Sandbox Code Playgroud)