https://kotlinlang.org logo
Title
c

chervak.av

11/28/2019, 7:51 PM
newbie question! Hello! please tell me how can I add char to string?
m

Milan Hruban

11/28/2019, 7:55 PM
hi, you should be able to use the plus operator
val someString = "abc"
val someChar = 'c'
val result = someString + someChar
//or better, string template
val result = "$someString$someChar"
c

chervak.av

11/28/2019, 8:02 PM
but if i need use something like someString +=someChar? add char to existing string
m

Milan Hruban

11/28/2019, 8:05 PM
then you need to declare the existing string as mutable -
var
, not
val
c

chervak.av

11/28/2019, 8:16 PM
tnx, i thought i need to use something like
stringbuilder
for this
k

karelpeeters

11/28/2019, 8:34 PM
If you're going to do this often (eg in a loop) it would be better to use a stringbuilder indeed.
t

tseisel

11/28/2019, 10:38 PM
Strings in Kotlin are immutable sequences of characters, just like in Java. Adding a new character to a string (with
+
or using the string template syntax) always results in a new String instance being created. If you need a mutable sequence of characters, you should use
StringBuilder
.