“Warning:(xx, xx) Kotlin: ‘T’ has a nullable upper bound. This means that a value of this type may be null. Using ‘T?’ is likely to mislead the reader”
But when I remove the ‘?’, I got:
“Condition ‘xxx == null’ is always false” or “Condition ‘xxx != null’ is always true”
I wanted to be able to check wheter is null or not.
Could you please show a sample code with this issue? It's hard to guess what's going on without some code. E.g. in the following code there are no warnings:
fun <T> nullable(value: T) {
if (value == null)
println("null")
else
println("not null")
}
As simple as your example, try to use that function.
suppress(“unchecked_cast”)
fun <T> nullable(): T {
return “something” as T
}
val a = nullable<String>()
if (a == null) // will always false
Then,
suppress(“unchecked_cast”)
fun <T> nullable(): T? { // ‘T’ has a nullable upperbound
return “something” as T
}
val a = nullable<String>()
if (a == null) // no more warning
Then,
suppress(“unchecked_cast”)
fun <T: Any?> nullable(): T {
return “something” as T
}
// The same thing happen, except adding T?, but then again ‘T’ has a nullable upperbound
val a = nullable<String>()
if (a == null) // will always false
Well, if it's solved for you, that's good. But I'm afraid there is something still not cleared.
fun await<T>(future: Future<T>): T = future.get()
fun fetchData(): Future<String> {}
fun use() { val data: String? = await(fetchData()) if (data == null) {
}
}
By declaring data as String? you don’t do any good. Even if null check is not highlighted, it will never be true, at least without fooling type system in some other place.
It’s similar to this:
fun use() {
val data: String? = ""
if (data == null) {
}
}
Though compiler doesn’t issue warning on null check, it’s in fact can never be null.
If I wanted the return to be not null, then I can just use infer. ( val data = await(fetchData() ). If it’s null it will still not throws NPE. But I cannot use if data == null.
If I wanted to be nullable, then just declare it explicitly. (val data: JsonObject? = await(fetchData()).Then I can check for if data == null.
So, the compiler already did the great job. It was me that was wrong from the beginning.