Tuesday 29 May 2018

Compound type

Sometimes it is necessary to express that the type of an object is a subtype of several other types. In Scala, this can be expressed with the help of compound types

In Java when we implement two interfaces, to call the method from each interface, we might need to pass multiple objects, This can be avoided by Scala's compound type.

  trait Batting {
    def batting: Unit = {
      println("Do Batting")
    }
  }

  trait Bowling {
    def bowling : Unit = {
      println("Do Bowling")
    }
  }

  class AllRounder extends Batting with Bowling {

    def battingAndBowling(allRounder: Batting with Bowling) :Unit = {
        allRounder.batting
        allRounder.bowling
    }

    battingAndBowling(new AllRounder)

  }

  In a class AllRounder, method battingAndBowling takes a parameter which can do Bowling and Batting.

  If we wanted to achieve same in Java, we might have to change method as:

    Javaish approach

    public void battingAndBowling(Batting bt, Bowling bo) {
      bt.batting();
      bo.bowling();
    }
    battingAndBowling(New AllRounder(), new AllRounder())
   
    Note, we are passing two objects to call a respective method from the respective interface.

    Surely, we can avoid this:

    public <T extends Batting & Bowling> void battingAndBowling(T allRounder) {
      allRounder.call();
      allRounder.feed();
    }


 Scala does same in an elegant way!

No comments:

Post a Comment