官术网_书友最值得收藏!

Companion object

In Java, Static Factory Methods are declared like this:

private static class MyClass { 
  
 // Don't want anybody to use it but me 
  private MyClass() { 
  } 
  
 // This will replace the public constructor 
  public static MyClass create() { 
    return new MyClass(); 
  } 
} 

They are called like this:

MyClass myClass = MyClass.create(); 

But in Kotlin, there's no such keyword as Static. Instead, methods that don't belong to an instance of a class can be declared inside a companion object.

We discussed the object keyword earlier, in the section Singletons. Now, we'll look at another use of this important keyword using the following example:

   class NumberMaster { 
       companion object { 
           fun valueOf(hopefullyNumber: String) : Long { 
               return hopefullyNumber.toLong() 
           }  
       } 
   } 

As you can see, inside our class, we have declared an object that is prefixed by the keyword companion.

This object has its own set of functions. What's the benefit of this? You may wonder.

Just like a Java Static method, calling a companion object doesn't require the instantiation of a class:

println(NumberMaster.valueOf("123")) // Prints 123 

Moreover, calling it on an instance of a class simply won't work, which is not the case with Java:

println(NumberMaster().valueOf("123")) // Won't compile 

A companion object may have a name-Parser, for example. But this is only for clarity of what the goal of this object is.
The class may have only one companion object.

By using a companion object, we can achieve exactly the same behavior that we see in Java:

private class MyClass private constructor() { 
 
    companion object { 
        fun create(): MyClass { 
            return MyClass() 
        } 
    } 
} 

We can now instantiate our object, as shown in the following code:

// This won't compile 
//val instance = MyClass() 
 
// But this works as it should 
val instance = MyClass.create() 

Kotlin proves itself a very practical language. Every keyword in it has a down-to-earth meaning.

主站蜘蛛池模板: 石景山区| 门源| 衡阳县| 平陆县| 图木舒克市| 金门县| 通许县| 漳浦县| 赤水市| 尤溪县| 中西区| 菏泽市| 张家口市| 甘谷县| 辉县市| 平乡县| 平果县| 东丽区| 日照市| 上饶县| 东城区| 金寨县| 布尔津县| 阳信县| 博罗县| 怀来县| 长泰县| 济阳县| 文昌市| 博湖县| 铁岭县| 鹰潭市| 汉寿县| 资源县| 尤溪县| 读书| 龙井市| 咸宁市| 隆回县| 瑞安市| 彭泽县|