How to "prepend" a Char to a String in Kotlin
Solution 1
What about using string templates, like this:
val prepended = "$char$string"
Solution 2
As of kotlin 1.5, there is an extension plus
operator
function defined on Char
, which can be used to concatenate a Char
with given String
. So you can do
val char = 'H'
val string = "ello World"
// Use the function call syntax
val result1 = char.plus(string)
// or use the operator syntax
val result2 = char + string
Related videos on Youtube
Comments
-
Eran Medan over 1 year
How in Kotlin can I prepend a
Char
to aString
?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 compileThe 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 usejava.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?)-
Andrey Breslav over 10 yearsYour second workaround looks rather good. The option with string templates suggested in the answers is equivalent and rather concise too. Nevertheless, we should consider adding Char.plus(String) to the standard library. I filed a request about it: youtrack.jetbrains.com/issue/KT-4371. Thanks for the report
-
Eran Medan over 10 years@AndreyBreslav this is great, I think
Char.plus(String)
will simply be more consistent with Java and Scala behavior, thanks for listening, Kotlin is getting to be my favorite Scala alternative :)
-
-
Mitchell Tracy over 6 yearsThis language makes me so happy.
-
Caesar about 2 yearsWith the plus operator the warning "Do not concatenate text displayed with
setText
. Use resource string with placeholders." is not shown!