If we have a val txt: kotlin.String = "1;2;3;"
and like to split it into an array of numbers, we can try the following:
val numbers = string.split(";".toRegex())
//gives: [1, 2, 3, ]
The trailing empty String
is included in the result of CharSequence.split
.
On the other hand, if we look at Java String
s, the result is different:
val numbers2 = (string as java.lang.String).split(";")
//gives: [1, 2, 3]
This time, using java.lang.String.split
, the result does not include the trailing empty String
. This behaviour actually is intended given the corresponding 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.
In Kotlin's version though, 0
also is the default limit
argument as documented here, yet internally Kotlin maps that 0
on a negative value -1
when java.util.regex.Pattern::split
is called:
nativePattern.split(input, if (limit == 0) -1 else limit).asList()
It seems to be working as intended but I'm wondering why the language seems to be restricting the Java API since a limit of 0
is not provided anymore.