次のコードをどのように改善できますか?今Scalaでコンストラクタを継承するにはどうすればよいですか?
def += (bitSet: BitSet): this.type = { this.bitSet | bitSet; this }
:私はキャストについてはサブクラスでキャストまたはオブジェクトスーパークラスとオブジェクトのサブクラス
class Superclass {
val bitSet = BitSet.empty
def += (bitSet:BitSet) = { this.bitSet | bitSet ; this }
def += (ints:Array[Int]) = { ints.foreach { bitSet += _ } ; this }
override def toString = bitSet.toString
}
object Superclass {
def apply(bitSet:BitSet) = new Superclass += bitSet
def apply(ints:Array[Int]) = new Superclass += ints
}
class Subclass extends Superclass {
override def += (bitSet:BitSet) = (super.+= (bitSet)).asInstanceOf[Subclass]
override def += (ints:Array[Int]) = (super.+= (ints)).asInstanceOf[Subclass]
}
object Subclass {
def apply(bitSet:BitSet) = new Subclass += bitSet
def apply(ints:Array[Int]) = new Subclass += ints
}
object SubclassTest extends App {
println(Subclass(Array(1,2,3)))
}
(一緒に
this.type
可能性を使用して)? – Pavelスーパークラスのシングルトン実装では、変換の兆候があるので、どこかのimplicitsを使うべきだと言います。 – Pavel
FPと命令型を混在させようとしています。通常、変更可能なオブジェクトに対しては 'this'を返さず、' + = 'は' Superclass'で実装されたように動作します。変更可能なオブジェクトを連結すると誤解を招く可能性があります。 –