- Hands-On Design Patterns with Kotlin
- Alexey Soshin
- 326字
- 2021-06-25 20:49:28
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.
- Learn ECMAScript(Second Edition)
- Learning Chef
- Responsive Web Design with HTML5 and CSS3
- Hands-On RESTful Web Services with Go
- Learning Apache Mahout Classification
- concrete5 Cookbook
- Android程序設計基礎
- C語言程序設計
- Mastering Python Design Patterns
- Learning Splunk Web Framework
- IBM RUP參考與認證指南
- Apache Solr for Indexing Data
- 趣學數據結構
- MySQL從入門到精通
- Spark for Data Science