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のbyの使い方

Posted at

プロパティ委譲(Delegated Properties)

Kotlinのbyの使い方がよく分かっていなかったのでメモします。by lazyby Delegates.observable などで利用し、「値の管理を別の仕組みに委譲する」ための文法です。

val data by lazy { loadData() }  

by lazy で初回だけ実行したい処理に使います。loadData() が実行された後はキャッシュした値を返します。

var count by Delegates.observable(0) { _, old, new ->
    println("count: $old  $new")
}

by observableで値の変化を監視したい時に使います。値が変わったタイミングでコールバックが走ります。

interface Printer {
    fun print()
}

class PrinterImpl : Printer {
    override fun print() = println("Hello")
}

class MyPrinter(printer: Printer) : Printer by printer

実装をそのまま利用したい時に便利です。実際の処理は全てprinterに任せています。再利用性が高まり複数のクラスで使いまわせやすいです。

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?