In scala multiple inheritance, how to resolve conflicting methods with same signature but different return type?

前端 未结 4 1862
时光说笑
时光说笑 2020-12-17 10:50

Consider the code below:

trait A {
  def work = { \"x\" }
}

trait B {
  def work = { 1 }
}

class C extends A with B {
  override def work = super[A].work
}         


        
4条回答
  •  -上瘾入骨i
    2020-12-17 11:14

    You can't do that.

    Look at this piece of code:

    val c = new C
    val a: A = c
    val b: B = c
    

    There is no way that both of these lines could work:

    val s: String = a.work
    val i: Int = b.work
    

    If we allowed such code to compile, one of these assignments would have to throw a ClassCastException or fail in another way. So, it simply isn't possible to resolve such conflict.

    I guess you have to workaround this with some form of delegation, maybe something like this:

    class C extends A {
      def toB = new B {
        //implement B methods by somehow delegating them to C instance
      }
    }
    

提交回复
热议问题