简体   繁体   中英

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...

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM