Scala - Extends multi class with parameters

时间:2016-12-02 05:27:30

标签: scala traits

I would like to make some classes like this.

class A(val a1: String) {
    def message() = println(a1)
}
class B(val b1: String) {
    def doB() = println(b1)
}
class C(val c1: String) {
    def something() = println(c1)
}
class AB(val a: String, val b: String) extends A(a) with B(b) {
    //                                               ^error
}
class AC..
class BC..

I tried to use trait but since trait cannot have any parameter, It made error too. How should I do to make somthing like this.

1 个答案:

答案 0 :(得分:1)

它会给你错误,因为trait没有构造函数。但您可以将其更改为trait这样的参数;

class A(val a1: String) {
  def message() = println(a1)
}

trait B {

  def b: String

  def doB() = println(b)
}

class AB(val a: String, val b: String) extends A(a) with B {
  //this should work                                               
}