-1

I've heard that let is used when you wish to perform a null safe operation on an Object by using the safe call operator ?..(according to this) But the question is why this:

fun main() {
    var s: String? = null
    s = s?.let{ it.toUpperCase() }
    println(s)
}

is preferred over this:

fun main() {
    var s: String? = null
    s = s?.toUpperCase() 
    println(s)
}

In my opinion the 2nd variant is easier to read and understand which makes let useless.

So what is the purpose of let function?

DevAs
  • 3
  • 2

1 Answers1

3

?.let() is not preferred over simple ?.toUpperCase(). But we can't always use the latter, most importantly, we very often need to invoke a function of another object:

s?.let { parse(it) }
file?.let { FileInputStream(it) }

In addition, I personally sometimes prefer ?.let() if there is a long chain of calls and null exists only at its beginning. I feel ?.let() is then better for code clarity:

post?.let { it.author.personalInfo.address.street }

Instead of:

post?.author?.personalInfo?.address?.street
broot
  • 21,588
  • 3
  • 30
  • 35