Reputation: 51199
I wrote my class with nullable argument
class MyClass(a: String? = null) {
var b: String
init {
if( a == null ) {
b = "N/A"
}
else {
b = a
}
}
}
and noticed, that IntelliJ warns about b = a
assignment
Smart cast to kotlin.String
Why is this warning and how to aoid it?
Upvotes: 6
Views: 4650
Reputation: 89608
This is not something to avoid, this is a language feature called a smart cast.
The compiler has detected that a
is a non-null value on a given code path, and therefore it's available to you with a non-nullable String
type, which lets you use it directly without having to worry about its nullability. If you didn't get a smart cast, you'd have to manually cast it from a String?
to a String
to call methods on it - or to assign it to a non-nullable variable, like in your case.
Another, perhaps easier example to understand when smart cast kicks in is with subclasses. Let's say you have Person
and Customer
classes, with only the latter having a getPurchases()
method.
In Java, you'd have to do the following to call said method:
if (p instanceof Customer) {
((Customer)p).getPurchases();
}
In Kotlin, you get a smart cast inside the if
block to the subtype that you've already made the check for:
if (p is Customer) {
p.getPurchases()
}
If you think about it, the cast from String?
to String
is the same mechanism at work - you're getting a smart cast to a more concrete type too.
if (a != null)
given an a
of type String?
is basically the same as
if (a is String)
Upvotes: 6
Reputation: 82017
It’s not a warning, just an information that the compiler knows your variable a
to be not null
. As a result, it can be used as a String
instead of nullable String?
and therefore without safe-operator e.g.
Otherwise, you needed to explicitly cast a: String?
to String
in order to make it assignable to the String
variable b
, as shown on the following screenshot:
Upvotes: 11