stringkotlincharchararray

CharArray joinToString keeps printing commas instead of S's


fun printRoom() {
    println("Cinema: ")
    val rows = 7
    val columns = 8
    val seats = CharArray(columns) { 'S' }.joinToString { " " }
    for (i in 1..rows) {
        println("$i" + " " + seats)
    }
}

any help will be appreciated. Im sure this is something simple im doing but I can't figure out why this keeps printing commas instead of S's


Solution

  • CharArray.joinToString has these parameters, all of which are optional and have default values:

    fun CharArray.joinToString(
        separator: CharSequence = ", ", 
        prefix: CharSequence = "", 
        postfix: CharSequence = "", 
        limit: Int = -1, 
        truncated: CharSequence = "...", 
        transform: ((Char) -> CharSequence)? = null
    ): String
    

    joinToString allows you to use your own separator, add your own prefix and postfix, have an optional custom limit on the joining, and have a custom string for when that limit is reached, and also optionally transform the Chars into some other String first, before joining them together.

    By passing in { " " }, you pass a lambda expression that simply returns the string " ". This corresponds to the transform parameter. Kotlin thinks that you want to transform every Char to the string " " first, and then join the " " together! Because you didn’t pass the separator parameter, the default value of ”, “ is used as the separator, which is why you see a lot of commas.

    What you intended on doing is passing " " as the separator parameter. Don't write a lambda:

    val seats = CharArray(columns) { 'S' }.joinToString(" ")
    

    You can also be very explicit about this and say:

    val seats = CharArray(columns) { 'S' }.joinToString(separator = " ")
    

    If you don't mind a trailing space, repeat also works:

    val seats = "S ".repeat(columns)