2

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?

1 Answer 1

4

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Hah, I though that this will be something like that, but still I'm a bit surprised as split is Kotlin function and I supposed that the type inference will handle that. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.