Default value for undefined case

Just because I’m curious, why does this needs to be undefined instead of absent (null)?
Especially when there are so much features in a language to deal with null?

I asume you have three options to specify undefined:

  • wrap the type: Kotlin does not provide Union-types yet, but the second best is sealed classes.

    sealed class Container<T>(
        protected val value :  T?, 
        val defined : Boolean
    ){
        object Undefined<T : Any> : Container<T>(
             null, defined = false
        )
        class Present<T>(val value : T) : Container<T>(
            value, defined = true
        )
    }
    
  • Change the type: add a specific field which tells if the type is present. Or use sealed classes again. You need to change the class for this, for both cases, every type needs to know about it, so it must be important…

  • Use a specific value for the type: use a specific instance (null-object pattern) or set the value itself to something that doesn’t make sense for the type (eg. -1 for age).
    Then you can add an extension function which checks if it is defined

    fun Person.asDefinedOrNull() : Person? = when(this){
        Person.Undefined -> null 
        else -> this
    }
    
2 Likes