abstract class A {
val message: String
}
class B extends A {
val message = "I'm an instance of class B"
}
trait C extends A {
def loudMessage = message.toUpperCase()
}
class D extends B with C
val d = new D
println(d.message) // I'm an instance of class B
println(d.loudMessage) // I'M AN INSTANCE OF CLASS B
abstract class A:
val message: String
class B extends A:
val message = "I'm an instance of class B"
trait C extends A:
def loudMessage = message.toUpperCase()
class D extends B, C
val d = D()
println(d.message) // I'm an instance of class B
println(d.loudMessage) // I'M AN INSTANCE OF CLASS B
Class D has a superclass(부모클래스) B and a mixin C
. Classes can only have one superclass but many mixins
(using the keywords extends and with
respectively). The mixins and the superclass may have the same supertype.
→ 수퍼클래스와 믹신 둘다 A라는 부모클래스를 동일하게 가질 수 있다는 것
→ 클래스를 합성하는 방법
mixins은 트레이트들이다. 즉 클래스를 합성하는데 쓰게 된다.
클래스 D는 B를 상속받으면서 C의 기능또한 활용가능하다.
abstract class AbsIterator {
type T
def hasNext: Boolean
def next(): T
}
abstract class AbsIterator:
type T
def hasNext: Boolean
def next(): T
Next, we’ll implement a concrete class (all abstract members T
, hasNext
, and next
have implementations):
class StringIterator(s: String) extends AbsIterator {
type T = Char
private var i = 0
def hasNext = i < s.length
def next() = {
val ch = s charAt i
i += 1
ch
}
}
class StringIterator(s: String) extends AbsIterator:
type T = Char
private var i = 0
def hasNext = i < s.length
def next() =
val ch = s charAt i
i += 1
ch
위에서 만든 absiterator를 상속
trait RichIterator extends AbsIterator:
def foreach(f: T => Unit): Unit = while hasNext do f(next())
→ 반환값없이 어떠한 연산을 하겠다.
class RichStringIter extends StringIterator("Scala") with RichIterator
val richStringIter = new RichStringIter
richStringIter.foreach(println)
class RichStringIter extends StringIterator("Scala"), RichIterator
val richStringIter = RichStringIter()
richStringIter.foreach(println)
→ with로 트레이트를 상속받아서 그 내의 함수를 사용가능