Scala没有类型类,在这种情况下,甚至不能使用继承的特征来模拟类型类,因为特征仅表示对象上的方法,这意味着它们必须被“拥有”一个类,所以你不能把一个“只接受一个字符串作为唯一参数的构造函数”的定义(这是在OOP语言中可能调用的“读取”)的特征。
相反,你必须自己模拟类型类。这是像这样做(在评论相当于Haskell代码):
// class Read a where read :: String -> a
trait Read[A] { def read(s: String): A }
// instance Read Person where read = ... parser for Person ...
implicit object ReadPerson extends Read[Person] {
def read(s: String): Person = ... parser for Person ...
}
然后,当你有依赖于类型的类的方法,你必须将其指定为隐式上下文:
// readList :: Read a => [String] -> [a]
// readList ss = map read ss
def readList[A: Read] (ss: List[String]): List[A] = {
val r = implicitly[Read[A]] // Get the class instance of Read for type A
ss.map(r.read _)
}
用户可能会喜欢的,易于使用的这样的多态方法:
object read {
def apply[A: Read](s: String): A = implicitly[Read[A]].read(s)
}
那么可以这样写:
val person: Person = read[Person]("Person(Bob,42)")
我不知道这个类的任何标准实现,特别是。
此外,免责声明:我没有Scala编译器,并且多年没有使用该语言,所以我不能保证此代码编译。
我在下面找到唯一的当今有用的答案,是最近描述酸洗scala库的:[scala酸洗库](http://stackoverflow.com/a/23610675/1509695)和[uPickle]( http://stackoverflow.com/a/28173416/1509695)。 – matanster