Single exclamation mark in Kotlin

What does a single exclamation mark mean in Kotlin? I've seen it a few times especially when using Java APIs. But I couldn't find it in the documentation nor on StackOverflow.


Solution 1:

They're called platform types and they mean that Kotlin doesn't know whether that value can or cannot be null and it's up to you to decide if it's nullable or not.

In a nutshell, the problem is that any reference coming from Java may be null, and Kotlin, being null-safe by design, forced the user to null-check every Java value, or use safe calls (?.) or not-null assertions (!!). Those being very handy features in the pure Kotlin world, tend to turn into a disaster when you have to use them too often in the Kotlin/Java setting.

This is why we took a radical approach and made Kotlin’s type system more relaxed when it comes to Java interop: now references coming from Java have specially marked types -- Kotlin Blog

Solution 2:

It's the notation for platform types:

T! means "T or T?"

Solution 3:

Platform Types

The type names or class names ending with single exclamation mark ! are called platform types in Kotlin. You find them when you are working in Kotlin with old Java code that doesn't contain nullability information.

Examples:

Nullable Information: Nullable Type

@Nullable String in Java is considered as String? by Kotlin.

Non-null Information: Non-null Type

@NotNull String in Java is considered as String by Kotlin.

No Information: Platform Type

String without annotations in Java is considered as String! by Kotlin.


How to deal with Platform Types?

You can work with a platform type either as a nullable or a non-null. The compiler will allow you to call all methods on this type. It’s your responsibility how to use them. If you know that the value can be null, you should compare it with null before you call methods on it. If you know it’s not null, you can use it directly but as in Java, you’ll get exception if your assumption about the nullability is wrong.

Note that you can't declare platform types in Kotlin code, they come only from Java code.


Inheritance and Platform Types

While overriding Java methods in Kotlin code, you have the option to declare parameters and return types as nullable or non-null. You need to choose this wisely, because if you decide to make the parameters non-null, the Kotlin compiler generates non-null assertions for these non-null parameters. And when next time you access this Kotlin code back from Java and you pass a null value, you'll get exception.

Hope that helps clearing all your doubts about Platform Types.