如果我们有一个val txt: kotlin.String = "1;2;3;",并且想要将其拆分成一个数字数组,我们可以try 以下操作:

val numbers = string.split(";".toRegex())
//gives: [1, 2, 3, ]

结果CharSequence.split中包括尾部空String.

另一方面,如果我们看看Java String,结果是不同的:

val numbers2 = (string as java.lang.String).split(";")
//gives: [1, 2, 3]

这一次,使用java.lang.String.split,结果不包括尾随的空String.此行为实际上是为给定相应的JavaDoc而设计的:

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

然而,在Kotlin的版本中,0也是默认的limit参数,如文档here所示,但在Kotlin内部,当java.util.regex.Pattern::splitcalled时,0将映射为负值-1:

nativePattern.split(input, if (limit == 0) -1 else limit).asList()

它似乎在按预期工作,但我想知道为什么该语言似乎在限制Java API,因为不再提供0的限制.

推荐答案

这个实现意味着,在Kotlin中丢失的是通过limit = 0实现的java.lang.String.split的行为.事实上,在我看来,删除它是为了实现Kotlin中可能的选项之间的一致性.

Consider a string a:b:c:d: and a pattern :.

看一看我们在Java中可以实现的功能:

limit < 0[a, b, c, d, ]
limit = 0[a, b, c, d]
limit = 1[a:b:c:d:]
limit = 2[a, b:c:d:]
limit = 3[a, b, c:d:]
limit = 4[a, b, c, d:]
limit = 5[a, b, c, d, ] (goes on the same as with limit < 0)
limit = 6[a, b, c, d, ]
...

It appears that the limit = 0 option is somewhat unique: it has the trailing : neither replaced by an additional entry, as with limit < 0 or limit >= 5, nor retained in the last resulting item (as with limit in 1..4).

It seems to me that the Kotlin API improves the consistency here: there's no special case that, in some sense, loses the information about the last delimiter followed by an empty string – it's left in place either as the delimiter in the last resulting item or as a trailing empty entry.

在我看来,Kotlin函数似乎更适合principle of least astonishment.相反,java.lang.String.split中的零限制看起来更像是修改方法语义的特殊值.负值也是如此,作为一个limit显然没有直观的意义,如果不深入研究Javadoc,它们也不太清楚.

Kotlin相关问答推荐

Kotlin:有限的并行性并不是限制并行性

处理合成层次 struct 中的深层按钮以切换视图

在Kotlin项目中使用Free Fair AspectJ插件(使用Gradle)

Criteria Api 中的 Kotlin 泛型

Webpack 配置未应用于 kotlin 多平台react 项目

如何为 Kotlin 中的每个循环设置以避免越界异常

Jetpack compose 可滚动表格

Kotlin - 创建指定长度的随机整数的 ArrayList?

SpringBoot 2.5.0 对于 Jackson Kotlin 类的支持,请在类路径中添加com.fasterxml.jackson.module: jackson-module-kotlin

如何在 android jetpack compose 中相互重叠列表项?

包括登录Elvis operator?

如何在主线程上使用 Kotlin 协程 await()

从代码块执行和返回(在 Elvis 运算符之后)

主机名不能为空

在调用Kotlin数据类中的超类构造函数之前访问函数

创建Spring和#180的实例;Kotlin中的参数化类型引用

使用导航组件在BottomNavigationView中传递参数

在kotlin中初始化类变量的正确位置是什么

判断EditText是否为空kotlin android

Dagger 2 androidx fragment不兼容类型