Examples of how to use 'let' in Kotlin

As a little note to self, here are a few let examples in Kotlin:

fun main(args: Array<String>) {

    fun toUpper(s: String?): String? = s?.toUpperCase()

    toUpper(null)?.let {
        // this will never be run
        println("toUpper(null) is: ${it}")
    }

    toUpper("emily")?.let {
        println("toUpper(emily) is: ${it}")
    }

    // `let` can return a value
    val hello = toUpper("Hannah")?.let {
        "Hello, ${it}"
    }
    println(hello)

}

The output looks like this:

toUpper(emily) is: EMILY
Hello, HANNAH

That’s all I have for today, but if you needed to see how to use let in Kotlin I hope it helps.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.