简体   繁体   English

Mixin在Scala中有什么好处?

[英]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. 我正在阅读用于MixinScala博客 ,但看不到它们在帖子中使用的代码的优势。 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: 首先,他们只在main方法中使用traits方法,所以我不明白为什么他们不能仅仅扩展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. 我已经在下面的代码中进行了尝试,仅扩展trait就可以访问trait和抽象类的方法。 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. 假设StringIterator是独立实现的。 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). 由于这个原因,您不能使StringIterator扩展特征,它不能被您修改(另一种常见情况,当您不希望类直接扩展特征时,例如,当您添加的功能仅对某些应用程序有用时,但其他人则没有)。

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? StringIteratorIntIteratorFileIteratorMyIteratorYourIterator ...那么您将扩展哪一个?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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