I was experimenting with setting uninitialized values and was trying to get the following to work. This is mostly a curiosity in the power (and limitations) of reified generics.
I was attempting to provide default values for optional parameters of data classes.
inline fun <reified T> uninitialized(): T = when (T::class) {
Long::class -> -1L // Type mismatch. Required: T Found: Long
String::class -> "" // Type mismatch. Required: T Found: String
// and so on...
else -> throw UnsupportedOperationException("No uninitialized value defined for " + T::class)
}
data class Thing(
var id: Long = uninitialized(),
var name: String = uninitialized() // and so on...
)
When when
includes is Type
clauses, Kotlin has smart casting. In this example, smart casting isn't kicking in so this will not compile.
Any ideas to accomplish something similar?
as T
can be applied to the wholewhen
at the very end ofuninitialized
– Whalebone