简体   繁体   中英

What are the benefits of Mixin in Scala?

I'm reading the Scala Blog for Mixin , and I don't see the advantage from the code they use on the post. First off they only use the traits method in the main method, so I don't see why they couldn't have just extended the trait:

object StringIteratorTest {
  def main(args: Array[String]) {
    class Iter extends StringIterator(args(0)) with RichIterator
    val iter = new Iter
    iter foreach println
  }
}

I've tried it with the code below, and just extending the trait gives me access to both the trait's and the abstract class' methods. So my question is: what is the advantage of using traits?

object Mixin extends App {

  class MixinTrait extends MixinAbstractClass{
    def traitPrint = println("I'm the trait")
  }

  abstract class MixinAbstractClass {
    def abstractPrint = println("I'm the abstract classs")
  }

  class MixinImplementation extends MixinTrait {}

  val obj = new MixinImplementation()
  obj.traitPrint
  obj.abstractPrint
}

The assumption is that StringIterator is implemented independently. Perhaps, it is a member of some library, and you want to "enrich" it by adding some utility methods.

You can't make StringIterator extend your trait for that reason, it's not modifiable to you (another common situation when you don't want the class to directly extend the trait like that is when the functionality you are adding is only useful to some applications of the class, but not others).

You could do it the other way around, and make the "rich" trait extend the original class, like you did in your example. That works, but what if there are more than one? StringIterator , IntIterator , FileIterator , MyIterator , YourIterator ... Which one would you extend then?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM