![]() So in Java, such methods had to be static members of a class, but in Kotlin we have companion object. ![]() ![]() There is no other way to distinguish it from “normal” methods (that don’t return an instance) at the first sight. The most important thing is for the static factory method name to go along with already known name patterns for this use-case. The above-mentioned names are fairly generic, but nothing should stop you from using more descriptive like forLanguageTag or fromBits like in previous examples. Typical static factory methods may look like this: Example usageĮven if the phrase “static factory method” sounds alien, I’m sure you saw it being used in code. We don’t have this possibility in Kotlin, but we can get a similar effect with companion object. To do so in Java, you would use the static keyword, which means that method is part of a class (understood as a type) rather than an object, and you can call it without creating an instance. Long story short, these are methods that create object instances based on supplied arguments (or even without them) and that you can call from anywhere without the need of having an instance of a class that contains them. This is also completely different from the Factory Method design pattern, don’t confuse those. But there are ways to achieve similar behavior to proposed by Joshua Bloch in Effective Java book - using static factory methods instead of constructors. There is a concise error in the title, there are no static methods in Kotlin.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |