How Scala Traits behave?

南笙酒味 提交于 2019-12-06 17:41:30

问题


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
}

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

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

How this can be possible?


回答1:


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.




回答2:


Try:

val myWriter = new Writer {}

I guess it needs an implementation, even if that implementation is empty



来源:https://stackoverflow.com/questions/39724284/how-scala-traits-behave

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!