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?

More than 5 years have passed since last update.

kotlinのSingleton

0
Posted at

Singletonとは

Singletonとはクラスのインスタンスが1つしか生成されないことを保証するものです。
kotlinではオブジェクト宣言よって作成されたオブジェクトは、シングルトンオブジェクトとなります。

kotlinのSingleton(object)の使い方

kotlinではオブジェクトを宣言することでSingletonのオフジェクトになります。

object SingletonObject {
    var text = "hello world"
}

fun main() {
    println(SingletonObject.text)
}

実行結果

hello world

objectはインスタンス化はできません。
よって、オブジェクト宣言によって作成されたオブジェクトは、シングルトンオブジェクトとなります。

object SingletonObject

fun main() {
    val singletonObject = SingletonObject() //インスタンス化できない。コンパイルエラーとなる
}

実行結果

Error:(8, 27) Kotlin: Expression 'SingletonObject' of type 'SingletonObject' cannot be invoked as a function. The function 'invoke()' is not found

継承

objectはスーパータイプを持つことができます。

interface MyInterface {
    fun bar()
    fun foo() {
        println("fun foo")
    }
}

object SingletonObject: MyInterface {
    override fun bar() {
        println("fun bar")
    }
}

fun main() {
    SingletonObject.bar()
    SingletonObject.foo()
}

実行結果

fun bar
fun foo
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?