Search code examples
kotlinconcatenation

How to convert concatenation to template in Kotlin


I am new to programming. Recently, I started learning Kotlin. I got a suggestion with this code:

var cont = "N"
var result:Int?
result = 45
println (cont + " + " + result)

It suggests converting this {" + "} to a template, but I do not know how?


Solution

  • In Kotlin, you can use string templates to remove all the concatenation symbols in your code. They always start with a $.

    For example in your code, you could have done this:

    println("$cont + $result")
    

    This would print the same result as your original code, just more concise and readable. This can even be done on arbitrary expressions you just have to wrap it in curly braces.

    For example:

    val cont = "ALEC"
    println("Hi ${cont.toLowerCase()}") //prints Hi alec
    

    As mentioned in the comments, IntelliJ will do this automagically by hitting ALT + Enter when the hint is suggested.