How in Kotlin can I prepend a Char
to a String
?
e.g.
fun main(args: Array<String>) { val char = 'H' val string = "ello World" val appendingWorks = string + char //but not what I want... //val prependingFails = char + string //no .plus(str:String) version val prependingWorkaround1 = char.toString() + string val prependingWorkaround2 = "" + char + string val prependingWorkaround3 = String(charArray(char)) + string }
When trying to call +
(e.g. plus
) on Char, there is no version that accepts a String on the right, so therefore 'H' + "ello World"
doesn't compile
The first workaround might be good enough but it's a regression for me from what works in Java: String test = 'H' + "ello World";
(compiles fine...)
I also don't like the last workaround, at least in the java.lang.String
I have a constructor that accepts a single char, or I can use java.lang.Character.toString(char c)
. Is there an elegant way in Kotlin to do so?
Was this discussed before (adding a plus(str:String)
overload to the Char object?)
A simple solution to append characters to the end of a String is using the + (or += ) operator. Alternatively, we can use the plus() function to concatenate a char with the given string.
Strings are immutable in Kotlin. That means their values cannot be changed once created. To replace the character in a string, you will need to create a new string with the replaced character.
There are different ways to concatenate strings in Kotlin. For example, we can use the $ operator or we can use the append() function or we can simply use the "+" operator to join two strings.
What Is String Interpolation in Kotlin? A string interpolation or interpolation expression is a piece of code that is evaluated and returns a string as a result. In Kotlin, string interpolation allows us to concatenate constant strings efficiently and variables to create another string.
What about using string templates, like this:
val prepended = "$char$string"
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