Kotlin let question?

#1

Hi, everyone I have a question.
I always use let method such as this
A?.Let {itA->
Log.v(“AAA”, $itA)
}
But my colleague has asked me why don’t write like that
A?.Let {
Log.v(“AAA”, $A)
}
Can anyone tells me that two methods same or different?

#2

Assuming that the $ you put is an error and in the second example you meant it instead of $A, none at all! The two examples are perfectly equal.
In the first case you just named the implicitly named it parameter of the lamba as A, but you could have called it whatever you wanted like:

a?.let { useCodeMarkDownPlease ->
    Log.v(“AAA”, useCodeMarkDownPlease)
}

Seriously tho, many in this forum are posting code as image or plain text. It makes me burn my eyes every time.

1 Like
#3
val aValue: Type? = ....
aValue?.let{ itA -> println(itA) }

In println method, if you pass “a”, its type is Type?
But if you pass “itA”, its type is Type, which is non-nullable.

This is because at the ?.let section, if your aValue is null, let will not be called, so in the lambda part it’s the non-nullable type captured. And if the println method accepts Type, which is non-nullable as its parameter, only when you pass itA can you pass compiling.

#4

I know. ?Let that just let no null value go in to the lambda, so in ?.let block area that value is not null.
So my question is
Var a :? String =null
a = “as”
a?.let{ println(a)}

Or

a?.let{ println(it)}
Are both methods same or different?

#5

Sorry, I’ve tried, println(a) can pass compiling due to smart-cast.
But when you failed to do smart-cast, you will fail compiling.

class StubClass {
   var a: Any? = null
   init {
      a = ...
   }
   private fun targetFunction(param: Any) = Unit
   fun method() {
       a?.let { targetFunction(it) } //passes compiling
       a?.let { targetFunction(a) }  //can't pass compiling
   }
}
#6

Besides, a?.let { fun(a) } is quite odd in natrual language.

A lets someone do something to itself.

vs

A lets someone do something to A.

which one do you think you will speak in natural language?

#7

I prefer to use it instead a.
That is my colleague question.
I don’t want to persuade him because he is stubborn.

#8

:rofl: Feel free to use my code snippet above to persuade him, he can’t even pass compiling in his way

#9

I don’t know. Maybe or maybe not. His choice I cannot change it. Haha.

#10

I think your full code looks similar to this:

val a: A? = getA()

a?.let { 
    // do stuff
} 

So in most cases you can omit creation of local variable:

getA()?.let { a-> // or it
    // do stuff
}

Even if you really need this local variable right now, later you can refactor code so that you can omit that variable. And this refactoring will be much easear to implement if you use it or named lambda parameter instead of captured local variable IMO.

#11

Thanks everyone to responds my question.
I always write it instead the parameter when I use let method.