本文介绍了Scala Traits 如何表现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了这个小型 Scala 示例以更好地理解特征.

I created this small Scala example for understand better traits.

trait Writer {
  def write(value: Int): Unit = {
    print("Writer")
  }
}

trait Hdd extends Writer {
  override def write(value: Int): Unit = {
    print("Hdd")
  }
}

trait File extends Writer {
  override def write(value: Int): Unit = {
    print("File")
  }
}

class TestClass extends App {
  (1)   val myWriter = new Writer with Hdd   // This line looks fine
  (2)   val myNewWriter = new Writer         // This line fail
}

据我所知,不可能实例化 Trait,因此第 (2) 行失败了.

In my understanding, it's not possible to instantiate a Trait, and for this reason the line (2) is failing.

但由于某种我无法理解的原因,第 (1) 行看起来不错.

But for some reason that I'm not able to understand, the line (1) looks fine.

这怎么可能?

推荐答案

是的,你说得对,在 Scala 中不能实例化一个 trait.一个 trait 不能实例化,只能混入.你需要一个类来实例化,什么时候您使用带硬盘的新写入器",它创建了一个匿名类,因此您的实例化看起来很好,并且没有给出任何错误.第二行出现错误,因为它只是一个特征,因此无法实例化.

Yes,you are right that a trait can not be instantiated in Scala.A trait cannot be instantiated, only mixed in. you need a class for instantiation and when you use "new writer with Hdd",it creates an anonymous class hence your instantiatation looks fine and does not give any error.And you get error for 2nd line as it is just a trait hence can't be instantiated.

这篇关于Scala Traits 如何表现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 10:06