「Kotlin」キーワードbyを使うサンプル

2020年12月27日

書式
class 子クラス(オブジェクト名: 親クラス) : 親クラス by オブジェクト名

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// インターフェース定義
interface Base {
fun outPut()
}
// インターフェースの実装
class BaseImpl(val x: Int) : Base {
override fun outPut() { outPut(x) }
}
// キーワード by
class Derived(b: Base) : Base by b
fun main(args: Array<String>) {
val b = BaseImpl(345)
Derived(b).outPut()
}
// インターフェース定義 interface Base { fun outPut() } // インターフェースの実装 class BaseImpl(val x: Int) : Base { override fun outPut() { outPut(x) } } // キーワード by class Derived(b: Base) : Base by b fun main(args: Array<String>) { val b = BaseImpl(345) Derived(b).outPut() }
// インターフェース定義
interface Base {   
    fun outPut()
}

// インターフェースの実装
class BaseImpl(val x: Int) : Base {
    override fun outPut() { outPut(x) }
}

// キーワード by 
class Derived(b: Base) : Base by b

fun main(args: Array<String>) {
    val b = BaseImpl(345)
    Derived(b).outPut() 
}

実行結果
>kotlinc sample.kt -include-runtime -d sample.jar
>kotlin sample.jar
345

Kotlin

Posted by arkgame