Kotlin. Overloading methods for type Null

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)
}

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

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).

1 Like

Thank you all for your advice!

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.

1 Like

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

setData(setNull())

?

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

1 Like