【发布时间】:2015-08-13 00:58:57
【问题描述】:
根据Erik Osheim's slide,他说继承可以解决与 typeclass 相同的问题, 但是提到继承有个问题叫:
脆弱的继承噩梦
说继承是
将多态性与成员类型紧密耦合
他是什么意思?
在我看来,继承擅长扩展,无论是改变现有类型的实现还是向接口添加新的成员类型(子类型)。
trait Foo { def foo }
class A1 extends Foo{
override def foo: Unit = ???
}
//change the foo implementation of the existing A1
class A2 extends A1 with Foo{
override def foo = ???
}
// add new type B1 to Fooable family
class Bb extends Foo{
override def foo = ???
}
现在就类型类而言:
trait Fooable[T] { … }
def foo[T:Fooable](t:T) = …
class Aa {…}
class Bb {…}
object MyFooable {
implicit object AaIsFooable extends Fooable[Aa]
implicit object B1IsFooable extends Fooable[Bb]
…
}
我看不出有任何理由更喜欢 Typeclass ,我是否遗漏了什么?
【问题讨论】:
-
如果您想将
Int添加到您的Foo家庭怎么办?你是怎么做到的? -
@Wei-ChingLin 这会给
error: illegal inheritance from final class Int -
@Kolmar 好,这是个问题。但是为什么
Int必须是最终的? -
继承的另一个问题是它只是第一个参数的参数(这是隐含的,因为 OOP 中的第一个参数是对象本身)。类型类在多个参数上是参数化的。想想
+。 -
我认为它是“静态”多次调度,根本不是继承的一个非常关键的原因。
标签: scala inheritance functional-programming typeclass