user1974753
user1974753

Reputation: 1457

String.split not compiling in Kotlin?

Driving me crazy!

I have the following simple snippet of code:

val text = "hello"
val splitStr = "l"
text.split(splitStr, false, 1)

But there is a compile error on the third line. It says:

None of the functions can be called with the arguments supplied.

Even though there is a split method in Strings.kt that takes these args:

public fun CharSequence.split(vararg delimiters: String, ignoreCase: Boolean = false, limit: Int = 0): List<String> =
    rangesDelimitedBy(delimiters, ignoreCase = ignoreCase, limit = limit).asIterable().map { substring(it) }

Any ideas on what the problem is here? If I omit the last two arguments in compiles, but I should be able to pass them in as I am doing...

Upvotes: 1

Views: 938

Answers (2)

Pamela Hill
Pamela Hill

Reputation: 99

Typically, a vararg parameter is the last parameter in a function signature, unless there are optional parameters. So this is a rather interesting case of their combination. Because with a vararg there may be multiple values, it's necessary to explicitly name the optional parameters.

For example, you can split on multiple delimiter strings:

val secondSplitStr = "e"
val result = text.split(splitStr, secondSplitStr, ignoreCase = false, limit = 1)

Just watch out for that limit = 1, it might not give the effect you want as the default is 0.

Upvotes: 1

user1974753
user1974753

Reputation: 1457

Ah, you have to name the arguments.

This compiles fine:

val count = text.split(skill, ignoreCase = false, limit = 1)

Strange though, when I have methods I wrote myself with named parameters with default values, I didn't have to specify the names when calling the method.

Upvotes: 2

Related Questions