2017-05-05 25 views
26

kotlinのクラス内のオブジェクトとコンパニオンオブジェクトの違いは何ですか?Kotlin:クラス内のオブジェクトとコンパニオンオブジェクトの相違

例:

class MyClass { 

    object Holder { 
     //something 
    } 

    companion object { 
     //something 
    } 
} 

Iはすでに含むパラメータ/方法が密接にそのクラスに関連している場合、そのコンパニオンオブジェクトは、使用しなければならない読み取ります。

しかし、なぜクラス内に通常のオブジェクトを宣言する可能性もありますか?コンパニオンとまったく同じように動作するため、名前が必要です。

「静的な」(私はJava側から)ライフサイクルの違いがありますか?

+0

シングルトンの場合は 'object'、静的メソッドの場合は' companion object'です。 [Kotlin - オブジェクトの宣言](https://kotlinlang.org/docs/reference/object-declarations.html#object-declarations)には、使い方の説明があります。 – ArtiomLK

答えて

15

オブジェクトはインターフェイスを実装できます。クラス内では、インターフェイスを実装しない単純なオブジェクトを定義することはほとんどの場合利点がありません。しかしながら、様々なインターフェース(例えばComparator)を実装する複数のオブジェクトを定義することは非常に有用であり得る。

ライフサイクルの面では、コンパニオンオブジェクトとクラスで宣言された名前付きオブジェクトの間に違いはありません。

+0

パーフェクト!あなたの説明をありがとう! – Poweranimal

+0

AFAIK初期化の順序に若干の違いがあります – Ilya

+0

違いは何ですか?私はコンパニオンが最初に初期化されたと推測します。なぜなら、それはそのクラスに結びついているからです。オブジェクトは後で呼ばれますか? – Poweranimal

2

コンパニオンオブジェクトは、静的メソッド/フィールドのようにコンパニオンオブジェクトの関数/プロパティを呼び出すことができるため、コンパニオンオブジェクトが存在します。そして、あなたのHolderが許可されている理由で、ネストされたオブジェクトの宣言が違法であるという理由はありません。時々便利になるかもしれません。

11
There are two different types of `object` uses, **expression** and **declaration**. 

**Object Expression** 

An object expression can be used when a class needs slight modification, but it's not necessary to create an entirely new subclass for it. Anonymous inner classes are a good example of this. 

    button.setOnClickListener(object: View.OnClickListener() { 
     override fun onClick(view: View) { 
      // click event 
     } 
    }) 

One thing to watch out for is that anonymous inner classes can access variables from the enclosing scope, and these variables do not have to be `final`. This means that a variable used inside an anonymous inner class that is not considered `final` can change value unexpectedly before it is accessed. 

**Object Declaration** 

An object declaration is similar to a variable declaration and therefore cannot be used on the right side of an assignment statement. Object declarations are very useful for implementing the Singleton pattern. 

    object MySingletonObject { 
     fun getInstance(): MySingletonObject { 
      // return single instance of object 
     } 
    } 

And the `getInstance` method can then be invoked like this. 

    MySingletonObject.getInstance() 

**Companion Object** 

A companion object is a specific type of object declaration that allows an object to act similar to static objects in other languages (such as Java). Adding `companion` to the object declaration allows for adding the "static" functionality to an object even though the actual static concept does not exist in Kotlin. Here's an example of a class with instance methods and companion methods. 

class MyClass { 
     companion object MyCompanionObject { 
      fun actsAsStatic() { 
       // do stuff 
      } 
     } 

     fun instanceMethod() { 
      // do stuff 
     } 
    } 

Invoking the instance method would look like this. 

    var myClass = MyClass() 
    myClass.instanceMethod() 

Invoking the companion object method would look like this. 

    MyClass.actsAsStatic() 


See the [Kotlin docs](https://kotlinlang.org/docs/reference/object-declarations.html) for more info. 
+1

ありがとうマイク!これが答えになるはずです。 –

+1

コンパニオンオブジェクトに名前がない場合は、コンパニオンオブジェクト内のメソッドを 'MyClass.MyCompanionObject.actsAsStatic()'または 'MyClass.Companion.actsAsStatic()'として使用する必要がありました。それは新しい変化ですか、私は間違ったことをしましたか?ありがとう。 – Sup

+0

これは受け入れられる回答である必要があります – onmyway133

2

オブジェクトまたはオブジェクト宣言は、初回アクセス時に遅延して初期化されます。

コンパニオンオブジェクトは、対応するクラスがロードされると初期化されます。 Kotlinは静的メンバーを本質的にサポートしていませんが、それは「静的」エッセンスをもたらします。

関連する問題