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?
Using + Operator The + operator is one of the widely used approaches to concatenate two strings in Kotlin. Alternatively, you can use the plus() function to concatenate one string at the end of another string.
Using StringBuilder With each concatenation using the + operator or plus() method, we get a new String object. In contrast, to avoid unnecessary String object creation, we can use a StringBuilder.
Using joinToString() function To concatenate multiple integers to a string, it is useful to create a utility function that accepts a vararg. The joinToString() function can join all vararg elements using a separator and transform function (to convert each integer to a string).
String templates are String literals that contain embedded expressions. For example, this code in Java: String message = "n = " + n; In Kotlin is just: val message = "n = $n" Any valid Kotlin expression may be used in a String template: val message = "n + 1 = ${n + 1}"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With