jaqxues
05/19/2020, 2:02 PMclass Preference<T : Any> private constructor(
val key: String,
val default: T,
val type: KClass<T>
)
// Extension Function
fun getPref(): T { // This should be a nullable generic set by the preference
// parse and return pref
}
Now, not every preference is not-null. So how can I omit <T: Any>
to get to <T>
so the preference itself can set itself nullable only via its type generic?
The problem is that KClass does not like <T> and requires <T: Any>
is there any smart way to get a not-null type generic from a nullable one? Or a reified function way to handle that?Michael de Kaste
05/19/2020, 2:23 PMclass Preference<T : Any> private constructor (
val key: String,
val default: T?,
val type: KClass<T>
)
Luca Clemente Gonzalez
05/19/2020, 2:27 PMjaqxues
05/19/2020, 2:27 PMval notNull: Preference<String>...
val nullablle: Preference<String?>...
so basically T, which is defined here above should be used in getPref to decide whether the preference is nullable or notnulljaqxues
05/19/2020, 2:27 PMLuca Clemente Gonzalez
05/19/2020, 2:28 PMjaqxues
05/19/2020, 2:28 PMLuca Clemente Gonzalez
05/19/2020, 2:28 PMLuca Clemente Gonzalez
05/19/2020, 2:29 PMLuca Clemente Gonzalez
05/19/2020, 2:30 PMjaqxues
05/19/2020, 2:30 PMLuca Clemente Gonzalez
05/19/2020, 2:30 PMjaqxues
05/19/2020, 2:30 PMjaqxues
05/19/2020, 2:32 PMfun doThis(): T? = ...
fun doThat(): T = ...
DecideThisThat would now have to return a nullable type
fun decideThisThat(): T? = if (nullable) doThis() else doThat()
Luca Clemente Gonzalez
05/19/2020, 2:32 PMjaqxues
05/19/2020, 2:34 PMclass Preference<T> private constructor(
val key: String,
val default: T,
val type: KClass<T!>
)
// Extension Function
fun getPref(): T { // This should be a nullable generic set by the preference
// parse and return pref
}
Basically this is what i want:
• T is nullable and default is nullable
• getPref now uses null-safe type generics (nullable if T of pref is nullable)
• KClass doesnt cry about a nullable generic
Problem: you cant just make T!jaqxues
05/19/2020, 2:36 PMMichael de Kaste
05/19/2020, 2:36 PMjaqxues
05/19/2020, 2:39 PMjaqxues
05/19/2020, 2:40 PMclass Data<T>(val data: T)
fun <T> Data<T>.get(): T = data
fun main() {
val example = Data<String?>("Hello")
example.data
val example2 = Data("Hello")
example2.data
}
jaqxues
05/19/2020, 2:41 PMexample.get()
is nullable, example2.get()
is not null
the nullability is defined by the type generic in the constructorjaqxues
05/19/2020, 2:41 PMjaqxues
05/19/2020, 2:50 PMKroppeb
05/19/2020, 6:19 PMcristiangm
05/19/2020, 9:06 PM