Blog Infos
Author
Published
Topics
Author
Published
Topics

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

Job Offers


    Senior Android Engineer

    Carly Solutions GmbH
    Munich
    • Full Time
    apply now

    Senior Android Developer

    SumUp
    Berlin
    • Full Time
    apply now

OUR VIDEO RECOMMENDATION

No results found.

Jobs

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..🛑
Error in IDE — Type argument is not within its bounds
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.

YOU MAY BE INTERESTED IN

YOU MAY BE INTERESTED IN

blog
It’s one of the common UX across apps to provide swipe to dismiss so…
READ MORE
blog
In this part of our series on introducing Jetpack Compose into an existing project,…
READ MORE
blog
This is the second article in an article series that will discuss the dependency…
READ MORE
blog
Let’s suppose that for some reason we are interested in doing some tests with…
READ MORE

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu