Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using underscore ("_") right after a variable in string templates in Kotlin

Tags:

kotlin

In Kotlin, I'm trying to create a filename dynamically that includes a type and a date like this:

var filename = "ab_$type_$date.dat"

However, the second underscore in between the variables is causing a compile error:

Kotlin: Unresolved reference: name_

I know I could concatenate the strings in the old fashion way:

var filename = "ab_" + type + "_$date.dat"

But I'm wondering if there is a different way to accomplish the same thing. Is there a way to escape special characters in string templates or any other way to get this to work?

like image 658
Armando Hoyos Avatar asked Jul 05 '16 22:07

Armando Hoyos


People also ask

What is string interpolation in Kotlin?

String interpolation in Kotlin allows us to easily concatenate constant strings and variables to build another string elegantly.

How do you split a string in Kotlin?

The standard solution to split a string in Kotlin is with the native split() function, which takes one or more delimiters as an argument and splits the string around occurrences of the specified delimiters. The split() function returns a list of strings.


1 Answers

Just wrap your expressions in curly braces:

var filename = "ab_${type}_${date}.dat"
like image 150
Ruslan Avatar answered Sep 20 '22 15:09

Ruslan