0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Kotlinのabstractとdelegateの挙動について

Last updated at Posted at 2024-05-06

Kotlin初心者です。
だれかAbstractとDelegateのどちらを選択するポイントを教えてぇ
Delegateはクラスの拡張みたいな説明文が多いね。

以下のサンプルコード9に対してAbstractとの差を記載
https://jp-seemore.com/app/14661/#toc2

Abstractのみコード記載、DelegateはURL参照

abstract class AbstractDoubleInt {

    var doubledValue: Int = 0

    open fun getValue(thisRef: Any?, property: KProperty<*>): Int {
        return doubledValue / 2
    }

    open fun setValue(thisRef: Any?, property: KProperty<*>, value: Int) {
        doubledValue = value * 2
    }
}

class MeClass : AbstractDoubleInt()

//Delegateのパターン
val my = MyClass()
my.doubleValue = 10
println(my.doubleValue)

// abstractの継承パターン
val me = MeClass()
me.setValue(10)
println(me.getValue())

どちらも同じ結果

image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?