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