Search code examples
androidkotlinnullletkotlin-null-safety

What is the difference between my variable name and 'it' when using 'let' in kotlin?


In the following code snippet, what is the difference between the two Codeblocks?
If I check with println(name==it), that returns true, so they must be referencing the same object, right?

However, when the name variable has a value, everything works, but once I set it to null, Codeblock 1 works (meaning, the let block simply will not be executed), but Codeblock 2 throws an error. Why does kotlin not just skip/ignore Codeblock 2, when nameis null?

fun main() {
    
    var name:String? = "Cedric"
    //name = null
    
    //Codeblock 1
    name?.let{
        println("The length of name is ${name.length}")
    }
    
    //Codeblock 1
    name?.let{
        println("The length of name is ${it.length}")
    }
    
}

Thank you very much, any help is appreciated.


Solution

  • Code block 2 actually gives a compile-time error, while code block 1 doesn't. I think it's just a weird linting bug, as the two cases should be treated the same.