Hey folks, question about `.let` and nullability. ...
# getting-started
j
Hey folks, question about
.let
and nullability. Code snippet:
Copy code
val foo : String? = "sample"
foo.let { it.toUpperCase() }
Results in:
Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type String?
k
The definition is:
Copy code
public inline fun <T, R> T.let(block: (T) -> R): R
So no, there's no restriction on the nullability of
T
.
The trick you can use to filter out nulls is
Copy code
foo?.let { it.toUpperCase() }
j
🤦‍♂️ ... the missing
?
...
k
But note that this has nothing to do with
let
specifically, it works just as well for other functions.
j
Thanks! I appreciate that. Forgot about leading
?
and was expecting some magic. Was about to blame Kotlin version upgrade. simple smile
m
Just remember that your code currently does nothing. toUpperCase does not modify the underlying string, but rather returns a new string with upper case. Also, your specific example can be shortened to
foo?.toUpperCase()
. IntelliJ or Detekt should warn about unnecessary
let