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

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.

主站蜘蛛池模板: 林周县| 宜章县| 通山县| 凤冈县| 石屏县| 清新县| 会同县| 宾阳县| 合川市| 金昌市| 淮南市| 拜城县| 修武县| 二连浩特市| 辛集市| 新兴县| 贵阳市| 滦平县| 永顺县| 仲巴县| 陵川县| 遂昌县| 饶河县| 外汇| 阿克| 锡林浩特市| 诏安县| 布拖县| 晴隆县| 永安市| 兴国县| 宁陵县| 扎囊县| 南溪县| 沾化县| 微博| 石渠县| 昌邑市| 饶河县| 武乡县| 荣昌县|