Mysterious Kotlin 'parameter non-null exception'

| 1 minute read | kotlin

This week I found myself confused by an exception when writing a simple extension method on Android’s TextView.

Consider the following extension method:

fun TextView.doSomething() {

}

This is about as simple as it could get - it has no parameters and returns nothing. However, when I tried to use it, I found myself with the following exception:

Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter $receiver

But that’s weird - it looks like there’s a parameter called $receiver which is null… Except, I don’t have a parameter at all! Turns out, the TextView I was using was null! The receiver mentioned in the error message refers to the class the extension is called on. 😮