简体   繁体   English

String.split无法在Kotlin中编译?

[英]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: 即使Strings.kt中有一个使用以下参数的split方法:

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. 通常,除非有可选参数,否则vararg参数是函数签名中的最后一个参数。 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. 因为使用vararg可能有多个值,所以必须显式命名可选参数。

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. 只需注意该限制= 1,因为默认值为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. 但是,很奇怪,当我有一些方法时,我使用默认值的命名参数编写了自己,而在调用该方法时不必指定名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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