abstract class Foo(val s: String) {
def this(i: Int) = this("" + (i+2))
}
私の知る限り、コンストラクタは継承されず、Javaのようにsuper
のサブクラスから二次コンストラクタを呼び出すことはできません。
彼らは単なる無駄なアーティファクトなのでしょうか、あるいはこの構造のためのいくつかの賢明なユースケースですか?
abstract class Foo(val s: String) {
def this(i: Int) = this("" + (i+2))
}
私の知る限り、コンストラクタは継承されず、Javaのようにsuper
のサブクラスから二次コンストラクタを呼び出すことはできません。
彼らは単なる無駄なアーティファクトなのでしょうか、あるいはこの構造のためのいくつかの賢明なユースケースですか?
scala> object Bar extends Foo(3)
defined module Bar
scala> Bar.s
res3: String = 5
サブクラスのプライマリコンストラクタは、必ずしもプライマリクラスではなくスーパークラスのコンストラクタの1つを呼び出す必要があります。あなたは洗練を追加した場合、@のcoubeatczechの回答に加えて、あなたはまた、抽象クラス(および特性)のインスタンスを作成することができます
abstract class A(s: String) {
def this(i: Int) = this(i.toString)
}
class B(i: Int) extends A(i)
、
scala> :paste
// Entering paste mode (ctrl-D to finish)
abstract class Foo(val s: String) {
def this(i: Int) = this("" + (i+2))
}
// Exiting paste mode, now interpreting.
defined class Foo
scala> val f = new Foo(23) {}
f: Foo = [email protected]
scala> f.s
res3: String = 25
私は「(上記の空の改善を示してきたが、 {} ")、通常、抽象メンバの実装を提供する、いくつかの追加定義を提供します。
scala> abstract class Bar { def bar : Int }
defined trait Bar
scala> val b : Bar = new Bar { def bar = 23 }
b: Bar = [email protected]
scala> b.bar
res1: Int = 23