Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 933
RS.Chamroeun Avatar asked Jun 05 '18 16:06

RS.Chamroeun


People also ask

How do you concatenate in Kotlin?

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.

How do you use StringBuilder in Kotlin?

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.

How do you concatenate int and string in Kotlin?

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).

What is string template Kotlin?

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}"


1 Answers

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.

like image 140
cela Avatar answered Sep 19 '22 05:09

cela