The difference between kotlin and Java string is separate from regex
If we have a Val TXT: kotlin String =“1; 2; 3;” And like to split it into digital arrays, we can try the following methods:
val numbers = string.split(";".toRegex()) //gives: [1,2,3,]
The trailing empty string is contained in charsequence In the result of split
On the other hand, if we look at Java strings, the results will be different:
val numbers2 = (string as java.lang.String).split(";") //gives: [1,3]
This time, use Java lang.String. Split, the result does not include trailing empty strings This behavior is actually given the corresponding Javadoc:
However, in the version of kotlin, 0 is also the default restriction parameter, as described here, but when Java util. regex. When pattern:: split is called, the internal kotlin maps the value to a negative value - 1:
nativePattern.split(input,if (limit == 0) -1 else limit).asList()
It seems to work as expected, but I wonder why the language seems to limit the Java API because it no longer provides the 0 limit
Solution
Implementation means implementing Java by passing the missing limit = 0 in kotlin lang.String. The act of splitting In fact, from my point of view, it is deleted to achieve consistency among possible options in kotlin
Consider a string a: B: C: D: and a pattern:
Look at what we can have in Java:
Limit < 0 → [a, B, C, D,] limit = 0 → [a, D] limit = 1 → [A: B: C: D:] limit = 2 → [a, B: C: D:] limit = 3 → [a, C: D:] limit = 4 → [a, D:] limit = 5 → [a,] (same as limit < 0) limit = 6 → [a,]
It seems that the limit = 0 option is somewhat unique: it has a trailing: it is neither replaced with additional entries, nor the limit < 0 or limit > = 5, nor retained in the last generated project (as in 1.. 4)
In my opinion, the kotlin API improves consistency here: in a sense, there is no special case to lose information about the last delimiter followed by an empty string - it remains in place as a delimiter in the last result item or as a trailing empty entry
IMO, kotlin function seems to be more suitable for principle of least atonement Instead, Java lang.String. The zero limit in split looks more like a special value that modifies the semantics of a method The same is true for negative values. Obviously, there is no intuitive meaning as a limitation. It is not clear if Javadoc is not mined