Kotlin. Overloading methods for type Null


#1

Good day.

I’m trying to implement an interface of this kind:

interface IDataConversions {
     fun setData (value: Boolean?)
     fun setData (value: Byte?)
     fun setData (value: Short?)
     fun setData (value: Int?)
     fun setData (value: Float?)
     fun setData (value: ByteArray?)
     fun setData (value: String?)
}

However, I noticed that in this case I would have to check in each method for Null
Is there an opportunity in Kotlin to implement something like this? :

interface IDataConversions {
     fun setData (value: "Null type????")
     fun setData (value: Boolean)
     fun setData (value: Byte)
     fun setData (value: Short)
     fun setData (value: Int)
     fun setData (value: Float)
     fun setData (value: ByteArray)
     fun setData (value: String)
}

#2

You could do Any? but that would allow complex objects as well


#3

Even if you could declare the function fun setData(value: Null), it wouldn’t be very useful.
Since there is only one value that could be passed, you might as well declare fun setData() without any arguments.
Notice that Kotlin doesn’t have multi-dispatch, so if you had something like:

var data: String?
...
setData(data)

there would be no correct overload to call. You would need to test the value and (smart) cast it to either String or Null. If it were null, there would be no point in passing the “value” as an argument.

You could have something like:

fun setData(value: Any?) = when (value) {
    null -> ...
    is Int -> ...
    is Boolean -> ...
    ...
    else -> throw IllegalArgumentException()
}

But this isn’t type safe, since any object can be passed as an argument. It would be type safe if Kotlin supported union types (like Ceylon).


#4

Thank you all for your advice!


#5

You could also do something like this:

interface IDataConversions {
    fun setNull()
    
    fun setData(value: Boolean)
    fun setData(value: Byte)
    // etc
    
    fun setData(value: Boolean?) { setData(value ?: return setNull()) }
    fun setData(value: Byte?) { setData(value ?: return setNull()) }
    // etc
}

It doubles the number of methods, but only in the interface - implementations can implement just the non-null versions.


#6

fun setData(value: Boolean?) { setData(value ?: return setNull()) }
If i understood - When value= null , result will be:

setData(setNull())

?


#7

No, it will just call setNull() without setData(), because the return causes the function to stop executing (like it does everywhere else).