Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save npryce/8218de4739681ba45dc79eda8b7683d4 to your computer and use it in GitHub Desktop.
Save npryce/8218de4739681ba45dc79eda8b7683d4 to your computer and use it in GitHub Desktop.
Taking a reference to an extension of a nullable type is possible through the non-nullable type, but probably not what you want!

E.g. the stdlib defines the following function:

fun CharSequence?.isNullOrBlank(): Boolean

You can take a reference to this extension function like this:

val isNullOrBlankFn = CharSequence?::isNullOrBlank

The type of isNullOrBlankFn is, as you'd expect, (CharSequence?)->Boolean.

You can also refer to isNullOrBlank like this:

val isNullOrBlankFn = CharSequence::isNullOrBlank

But that gives isNullOrBlankFn the type (CharSequence)->Boolean -- it cannot be applied to nullable CharSequences.

This is allowed because CharSequence is a subtype of CharSequence?, and therefore a CharSequence can be passed wherever CharSequence? is allowed.

This also lets you refer to the isNullOrBlank extension function like this: String?::isNullOrBlank or even String::isNullOrBlank.

@erokhins
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment