I found this question which implements a null object pattern in Kotlin in a certain way. I usually do it a little different in Java:
class MyClass {
static final MyClass INVALID = new MyClass();
public MyClass() {
// empty
}
}
in this way, I can always use MyClass.INVALID
as the null object.
How can I achieve this style in Kotlin?
I fiddled with something like this:
data class MyClass(val id: Int) {
object INVALID: MyClass {
}
}
but that doesn't even compile.
One way you could achieve this is by using a companion object
. Because the members of the companion object can be called by using simply the class name as the qualifier. You could do;
data class MyClass(val id: Int) {
companion object {
@JvmStatic
val nullInstance = MyClass(0) //0 or any intended value
}
}
//invocation
val a = MyClass.nullInstance
val b = MyClass.nullInstance
print(a == b) //prints true because these are equavalent to Java's static instances.
Here I have annotated that nullInstance
as @JvmStatic
to have it generated as a real static member.
https://kotlinlang.org/docs/reference/object-declarations.html