以下 Haskell 类型类和实例:
class Able a where
able :: a -> Int
instance Able Int where
able x = x
通常像这样翻译成 Scala:
trait Able[A] {
def able(a: A): Int
}
implicit object AbleInt extends Able[Int] {
def able(a: Int) = a
}
在 Haskell 中,我现在可以定义一种包罗万象的实例,从而为所有 Maybe 类型创建一个实例:
instance Able a => Able (Maybe a) where
able (Just a) = able a
able Nothing = 0
这定义了Able
for Maybe Int
、Maybe Bool
等的实例,前提是存在Able
for Int
、Bool
等的实例。
在 Scala 中如何做到这一点?