companion object のメリットがイマイチ理解できません。
companion objectはJavaだとstaticに相当するとのことですが、
JavaからKotlinへstaticメソッドをIDEで変換してみたら次のようになりました。
Kotlin
1object Test { 2 3 fun testMethod() { 4 5 } 6}
companion object というキーワードが出てきません。
また、objectとcompanion objectの違いを調べるために、次のようなコードを書いてみました
Kotolin
1class Test1 { 2 companion object { 3 fun test1Method() { 4 println("1") 5 } 6 } 7} 8 9class Test2 { 10 object Test2Inner { 11 fun test2Method() { 12 println("2") 13 } 14 } 15} 16 17class Test3 { 18 companion object Test3Inner { 19 fun test3Method() { 20 println("3") 21 } 22 } 23} 24 25fun main(args: Array<String>) { 26 Test1.test1Method() 27 28 Test2.Test2Inner.test2Method() 29 30 Test3.Test3Inner.test3Method() 31 Test3.test3Method() 32}
companion objectもobjectも、ほぼ同じ動作をしました。
唯一の違いは、objectの方がメソッドの呼び出すときに、冗長な表現になってしまうことくらいです。
companion objectのメリット、objectとcompanion objectの違いはなんですか?

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/02/26 06:42
2018/02/26 07:01
2018/02/26 07:03
2018/02/26 10:47
2018/02/26 12:08