Recently, I worked with Java-based SDKs. They updated some layers in the SDK to Kotlin, specifically the interface exposed to clients.
Internally, they still use Java a lot. As I was testing the codebase after updating to the latest SDK, I encountered a crash 💥 with the following logs:
java.lang.NullPointerException:
Parameter specified as non-null is null: method com.*.*.VM$1.onSuccess,
parameter resul
Since I didn’t know about the default upper bound of Generics in Kotlin, I wondered why I was getting NullPointerException
[NPE].
Let’s analyze the code and learn why upper-bound is so important
interface AuthListener<T> {
//interface AuthListener<T:Any?> {
fun onSuccess(result:T)
fun onFailure(e:Exception)
}
Maybe you’re in the same boat as me in feeling that <T> is
non-nullable
like the way we declare non-nullable
properties without ?
val s: String // T
val s: String? // T? -> not allowed
It’s not because of the default upper bound
is nullable
🤯
The default upper bound (if there was none specified) is Any? -> Nullable
- Check the Kotlin docs here to learn more about it.
Job Offers
Non-nullable generics
So, if you want to define non-nullable
Generics then you need to explicitly define the upper bound in the declaration like 👇
interface AuthListener<T:Any> {
fun onSuccess(result:T)
fun onFailure(e:Exception)
}
- If you try to use a
type outside the bounds after setting the upper bound, the IDE will also show an error..🛑
Using Generic types with properties
T?
is allowed in the use of T
, not the declaration of T
.
- Valid use of
T
interface AuthListener<T:Any> {
// Nullable property
val CurrentState:T?
// Nullable generic function parameter
fun onSuccess(result:T?)
fun onFailure(e:Exception)
}
Properties/parameters can be
nullable
regardless of the upper bound’s non-nullability enforcement.
Let’s Connect
https://www.linkedin.com/in/navczydev/
https://github.com/navczydev?source=post_page—–b00a8cc1166c——————————–
References
https://kotlinlang.org/docs/generics.html?source=post_page—–b00a8cc1166c——————————–#upper-bounds
https://kotlinlang.org/docs/generics.html?source=post_page—–b00a8cc1166c——————————–