예제출처: 허준영교수님 github
data class Complex(val real: Double, val img: Double) {
operator fun plus(other: Complex): Complex
= Complex(real + other.real, img + other.img)
override fun toString(): String = "$real+${img}i"
}
operator fun Complex.minus(other: Complex): Complex
= Complex(real - other.real, img - other.img)
fun main() {
val c1 = Complex(1.0, 1.0)
val c2 = Complex(2.0, 2.0)
val c3 = c1 + c2
println(c3) // 3.0 + 3.0i
println(c3 == Complex(3.0, 3.0)) // true
}
by
키워드로 위임 지원예제출처: 허준영교수님 github
interface Base {
fun print()
fun printHello()
}
class BaseImpl(val x: Int) : Base {
override fun print() { print(x) }
override fun printHello() { println("Hello")}
}
class Derived(val b: Base) : Base by b {
override fun print() {
b.print()
println("ok")
}
}
// fun main() { // kts에서 작성
val b = BaseImpl(10)
val d = Derived(b)
d.print() // 10ok
d.printHello() // Hello // Derived 에서 구현하지 않았으나 b의 것을 사용
// }