Lukas Forst
Lukas Forst

Reputation: 842

Kotlin spread operator behaviour on chars array

I have been using Kotlin for some time now, but I just found out that when I would like to use spread operator on the array of chars and pass it to the split function, it does not work.

fun main() {
    val strings = arrayOf("one", "two")

    val stringSplit = "".split("one", "two")
    val stringsSplit = "".split(*strings)

    val chars = arrayOf('1', '2')

    val charSplit = "".split('1', '2')
    val charsSplit = "".split(*chars) // this is not possible
}

produces following error (same during the build and same in the official try kotlin repl) produced error

Am I doing something wrong?

Upvotes: 2

Views: 480

Answers (1)

Giorgio Antonioli
Giorgio Antonioli

Reputation: 16214

This happens because in Kotlin Array<Char> is equal to Character[] in Java, not to char[] in Java.

To use the spread operator on an array of characters and pass it to a vararg Char parameter, you need to use CharArray which is equal to char[] in Java.

fun main() {
    val strings = arrayOf("one", "two")

    val stringSplit = "".split("one", "two")
    val stringsSplit = "".split(*strings)

    val chars = charArrayOf('1', '2')

    val charSplit = "".split('1', '2')
    val charsSplit = "".split(*chars) // this is not possible
}

Upvotes: 4

Related Questions