0

I am facing issue with the code snippet, it says there is a conflict for func function in traits A and B

//Tried the below code:

trait A{
  def func(): Unit = {
    println("Inside trait A")
  }
}
trait B{
 def func(): Unit = {
    println("Inside trait B")
  }
}
class C extends A with B{
 //super[A].func()
}
object Sample extends App{
  val ob = new C()
  }
Rocky
  • 13
  • 2

1 Answers1

3

The error is

class C inherits conflicting members:
  def func(): Unit (defined in trait A) and
  def func(): Unit (defined in trait B)
  (note: this can be resolved by declaring an `override` in class C.)

You can override the member as the error message suggests:

class C extends A with B {
  override def func(): Unit = super[A].func() // Inside trait A
}

or

class C extends A with B {
  override def func(): Unit = super[B].func() // Inside trait B
}

If you don't specify any parent trait in super[...] then the choice of method implementation will depend on the order of parents:

class C extends A with B {
  override def func(): Unit = super.func() // Inside trait B
}

or

class C extends B with A {
  override def func(): Unit = super.func() // Inside trait A
}

Linearization order in Scala

Scala stackable traits

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66