Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling different methods from different traits in scala with multiple inheritance

Let's take the following example

trait Drawable {
  def draw
  def paint
}

trait Cowboy extends Drawable {
  override def draw() { println("Bang!") }
  override def paint(){ println("I need this to be painted")}
}

trait Artist extends Drawable {
  override def draw() { println("A pretty painting") }
  override def paint(){ println("I don't want this to be painted")}
}

class CowboyArtist extends Cowboy with Artist

object Main extends App {
  (new CowboyArtist()).draw() // A pretty painting
  (new CowboyArtist()).paint() // I don't want this to be painted
}

Here, Artist and Cowboy inherit Drawable and override the methods draw and paint. CowboyArtist inherits both Cowboy and Artist in the same order. From what I have read, scala determines which method to be called based on the order in which its inherited and the methods from the right most trait would be executed.

But what if I want one of the method to be called from the one trait which another method from another trait, as you see the example, I want the draw method to be executed from Artist trait but I want the paint method to be executed from the Cowboy trait.

Is this possible? If not what is the workaround?

like image 422
Rahul Avatar asked Mar 14 '23 19:03

Rahul


1 Answers

Sure, just use:

class CowboyArtist extends Cowboy with Artist {
    override def paint = super[Cowboy].paint
}

super[Trait] allows you to choose exact trait from linearization you want to call.

So now:

scala> (new CowboyArtist()).paint()
I need this to be painted

scala> (new CowboyArtist()).draw()
A pretty painting

P.S. you can use super[Trait] inside traits as well, so you can create a mixin with correct prioritization before mixing it into class:

trait CowboyArtistMixin extends Cowboy with Artist{
    override def paint = super[Cowboy].paint
}

class CowboyArtist extends CowboyArtistMixin
like image 123
dk14 Avatar answered Mar 18 '23 03:03

dk14