Kotlinのオブジェクト

Kotlinのオブジェクト

1. 前書き

Kotlinは他の言語から多くのアイデアを借りました。そのような構成の1つはobject.です

この簡単な記事では、オブジェクトとは何か、どのように使用できるかを説明します。

2. Kotlinのオブジェクト

Kotlinでは、ほとんどすべてのJVM言語と同様に、オブジェクト指向プログラミングモデルのコアとしてclassの概念があります。 Kotlin introduces the concept of an object on top of that.

classは、必要に応じてインスタンス化でき、必要な数のインスタンスを許可する構造体を表しますが、an object instead represents a single static instanceは、この1つのインスタンスを超えることも少なくすることもできません。

これは、シングルトンオブジェクトやカプセル化のための機能の単純なパッケージ化など、さまざまな手法に役立ちます。

object SimpleSingleton {
    val answer = 42;
    fun greet(name: String) = "Hello, $name!"
}

assertEquals(42, SimpleSingleton.answer)
assertEquals("Hello, world!", SimpleSingleton.greet("world"))

Objects also offer full support for visibility modifiers、他のクラスと同様にデータの非表示とカプセル化を可能にします。

object Counter {
    private var count: Int = 0

    fun currentCount() = count

    fun increment() {
        ++count
    }
}
Counter.increment()
println(Counter.currentCount())
println(Counter.count) // this will fail to compile

さらに、objects can extend classes and implement interfaces。 そうすることで、それらは事実上、期待どおりの親クラスのシングルトンインスタンスになります。

これは、ステートレス実装があり、毎回新しいインスタンスを作成する必要がない場合に非常に役立ちます。 Comparator:

object ReverseStringComparator : Comparator {
    override fun compare(o1: String, o2: String) = o1.reversed().compareTo(o2.reversed())
}

val strings = listOf("Hello", "World")
val sortedStrings = strings.sortedWith(ReverseStringComparator)

3. コンパニオンオブジェクトとは何ですか?

コンパニオンオブジェクトは、基本的に標準のobject定義と同じですが、開発を容易にするためのいくつかの追加機能があります。

コンパニオンオブジェクトは、常に別のクラス内で宣言されます。 Whilst it can have a name, it doesn’t need to have one、この場合、自動的にCompanionという名前になります。

class OuterClass {
    companion object { // Equivalent to "companion object Companion"
    }
}

Companion objects allow their members to be accessed from inside the companion class without specifying the name

同時に、クラス名の接頭辞を付けると、クラスの外部から可視メンバーにアクセスできます。

class OuterClass {
    companion object {
        private val secret = "You can't see me"
        val public = "You can see me"
    }

    fun getSecretValue() = secret
}

assertEquals("You can see me", OuterClass.public)
assertEquals("You can't see me", OuterClass.secret) // Cannot access 'secret'

4. 静的フィールド

The main use for companion objects is to replace static fields/methods known from Java。 ただし、これらのフィールドは、結果のクラスファイルにそのまま自動的に生成されるわけではありません。

それらを生成する必要がある場合は、代わりにフィールドで@JvmStaticアノテーションを使用する必要があります。これにより、期待どおりにバイトコードが生成されます。

class StaticClass {
    companion object {
        @JvmStatic
        val staticField = 42
    }
}

これを行わないと、静的フィールドstaticFieldにJavaコードから簡単にアクセスできません。

Adding this annotation generates the field exactly as needed for a standard static field, allowing for full interoperability from Java if necessary

これは、上記がStaticClassクラスでstaticメソッドgetStaticField()を生成することを意味します。

5. 結論

Kotlinのオブジェクトは、使用できる追加のレイヤー全体を追加し、コードをさらに合理化し、開発を容易にします。

コンパニオンオブジェクトはこれをさらに進め、メンテナンスと操作が簡単なクリーンなコードを実現します。

いつものように、コードスニペットはover on GitHubにあります。