Reputation: 1024
Given the simple class:
data class Optional<T>(val value: T?)
I can define generic function and value extensions as follows:
fun <T> T?.makeOptional() = Optional(this) // Compiles ✅
val <T> T?.optional get() = Optional(this) // Compiles ✅
I can also define global generic functions:
fun <T> makeOptionalNull() : Optional<T> = Optional(null) // Compiles ✅
However I CAN'T define an equivalent global generic value to this last function:
val <T> optionalNull : Optional<T> = Optional(null) // Compilation Error ❌
// ^ Type parameter of a property must be used in its receiver type
A global non-generic value is totally fine though:
val stringNull : Optional<String> = Optional(null) // Compiles ✅
How can I create a global generic value similar to the one above? Is it even possible?
Upvotes: 1
Views: 356
Reputation: 5002
Your problem can be solved the following way:
data class Optional<out T>(val value: T?) // <- note the 'out' modifier here
val optionalNull: Optional<Nothing> = Optional(null)
// and use it as follows:
val myOptionalVariable: Optional<String> = optionalNull // assignable thanks to 'out' modifier
Upvotes: 1