2016/12/21の30分 Kotlinメモ🍥

2016/12/21の30分 Kotlinメモ🍥

書いてるコードは雑にここにあります。

github.com

Kotlinスタートブック -新しいAndroidプログラミング を引き続き読んでる。

Kotlinスタートブック -新しいAndroidプログラミング

Kotlinスタートブック -新しいAndroidプログラミング

Object Expressions

kotlinlang.org

objectね!

なんか色々できるので、どんな用途で使うのがいいんだろーと悩む🤔

きっといつか答えが出るだろう...!

Interface

kotlinlang.org

Javaと基本同じだけど、プロパティを持てることに驚いたぞ!!

interface BucketKai {
    fun fill()
    fun drainAway()
    fun pourTo(that: BucketKai)

    // interfaceはプロパティを持てる
    // プロパティはオブジェクトの内部にあるものではなく、境界にあるもの
    // 変数のように見えるが、実際のデータの持ち方は規定しない
    // 実装するオブジェクトの実装次第になる
    val capacity: Int
    var quantity: Int
}

オブジェクト式で生成するとこんな感じで実装して使える。

fun createBucketKai(_capacity: Int): BucketKai = object : BucketKai {

    // プロパティにもoverrideがつく
    override val capacity = _capacity

    // プロパティは必ず初期化しないといけない
    override var quantity = 0

    override fun fill() {
        quantity = capacity
    }

    override fun drainAway() {
        quantity = 0
    }

    override fun pourTo(that: BucketKai) {
        val thatVacuity = that.capacity - that.quantity
        if (quantity <= thatVacuity) {
            that.quantity = quantity
            drainAway()
        } else {
            that.fill()
            quantity -= thatVacuity
        }
    }
}

val bucketKai1 = createBucketKai(7)
val bucketKai2 = createBucketKai(4)

bucketKai1.fill()
bucketKai1.pourTo(bucketKai2)
println(bucketKai1.quantity) // 3
println(bucketKai2.quantity) // 4

Class

上で使ったInterface BucketKaiをクラスで実装するとこんな感じ。

class BucketImpl(override val capacity: Int) : BucketKai {

    override var quantity = 0

    override fun fill() {
        quantity = capacity
    }

    override fun drainAway() {
        quantity = 0
    }

    override fun pourTo(that: BucketKai) {
        val thatVacuity = that.capacity - that.quantity
        if (quantity <= thatVacuity) {
            that.quantity = quantity
            drainAway()
        } else {
            that.fill()
            quantity -= thatVacuity
        }
    }
}

まとめ

どの絵文字使ってないか忘れてきたぞい...🍥