Question

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

Was it helpful?

Solution

What about using string templates, like this:

val prepended = "$char$string"

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top