我正在 Scala 中编写一些代码,这些代码依赖于我在参数上看不到的类型参数。
def read[T](json: String)(implicit m: Manifest[T]): T = {
if (m <:< manifest[Map[String, Any]]) {
JsonParser.jsonToMap(json).asInstanceOf[T]
} else {
throw new UnsupportedOperationException("Not implemented for type %s".format(m))
}
}
除了我正在编写自己的 json 框架这一事实之外,这可能是一个非常糟糕的主意......
我可以使用 case 语句代替 if 语句吗?还是我应该换个方向思考?
最佳答案
在这种情况下,您想对 list 或类(或更一般地类型大小写)使用测试序列,更好的想法是使用类型类。在这种特殊情况下,它看起来像,
// Type class
trait JsonReader[T] {
def apply(json : String) : T
}
// Type class instance for type Map[String, Any]
implicit def mapReader = new JSonReader[Map[String, Any]] {
def apply(json : String) =
JsonParser.jsonToMap(json).asInstanceOf[Map[String, Any]]
}
def read[T](json : String)(implicit reader : JsonReader[T]) : T = reader(json)
您应该为您关心的所有类型添加类型实例。
您现在可以按如下方式调用读取函数,
read[Map[String, Any]](... some json ...)
请注意,现在如果您尝试使用与未提供类型类实例的类型相对应的类型参数来调用它,结果将是编译时错误,而不是 UnsupportedOperationException
在运行时。
关于scala - 是否可以匹配 Scala 中 list 的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9060038/