我在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))
}
}
Run Code Online (Sandbox Code Playgroud)
除了我正在编写自己的json框架之外,这可能是一个非常糟糕的主意......
我可以使用case语句而不是if语句,还是应该在不同的方向思考?
在这种情况下,如果你觉得想要对清单或类使用一系列测试(或更普遍地输入套管),那么更好的想法是使用类型类.在这种特殊情况下,它看起来像,
// 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)
Run Code Online (Sandbox Code Playgroud)
您应该为您关心的所有类型添加类型实例.
您现在可以按如下方式调用读取函数,
read[Map[String, Any]](... some json ...)
Run Code Online (Sandbox Code Playgroud)
请注意,现在如果您尝试使用与未提供类型类实例的类型对应的类型参数调用它,则结果将在编译时而不是UnsupportedOperationException在运行时出错.