Search code examples
androidkotlinkotlin-android

What does the single exclamation "!" mean after the type in Kotlin?


I'm learning to Develop Android Apps using Kotlin. I previously used to Develop using Java. While coding in Android Studio, I can see that the return types, parameters, etc. used in the Lambdas, methods, etc. are written as View!.

I know that the ? after the type in Kotlin means a Nullable type. Though what does the ! mean.

For example:

val item = mySpinner.selectedItem

The return type is Any! What does the ! mean? Is it the same as a Nullable type i.e. Any? ? Thanks.


Solution

  • It's a platform type indicating that Kotlin is not sure whether it will be null or not null, it's like saying "maybe".

    platform types can't be mentioned explicitly in the program, so there's no syntax for them in the language. Nevertheless, the compiler and IDE need to display them sometimes (for example, in error messages or parameter info), so there is a mnemonic notation for them:

    • T! means "T or T?",
    • (Mutable)Collection! means "Java collection of T may be mutable or not, may be nullable or not",
    • Array<(out) T>! means "Java array of T (or a subtype of T), nullable or not"

    And because it can either be null or not null, it is up to you how you will treat it.

    Also check this another post