Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

473
Views
Why does Kotlin's split("") function result in a leading and trailing empty string?

I'm a Java developer who tried Kotlin and found a counterintuitive case between these two languages.

Consider the given code in Kotlin:

"???".split("")  # gives ["", "?", "?", "?", ""]

and the same in Java:

"???".split("")  # gives ["?", "?", "?"]

Why does Kotlin produce a leading and trailing empty space string in the resulting array? Or does Java always removes these empty strings, and I just wasn't aware of that?

I know that there is the toCharArray() method on each Kotlin String, but still, it's not very intuitive (maybe the Java developers should give up old habits from Java which they were hoping to reuse in a new language?).

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You need to filter out the first and last element:

"???".split("").drop(1).dropLast(1)

Check out this example:

"".split("")   // [, ]

Splits this char sequence to a list of strings around occurrences of the specified delimiters.

See https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/split.html

over 4 years ago · Santiago Trujillo Report

0

This is because the Java split(String regex) method explicitly removes them:

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.

split(String regex, int limit) mentions:

When there is a positive-width match at the beginning of this string then an empty leading substring is included at the beginning of the resulting array. A zero-width match at the beginning however never produces such empty leading substring.

"" is a zero-width match. Not sure why you consider toCharArray() to not be intuitive here, splitting by an empty string to iterate over all characters is a roundabout way of doing things. split() is intended to pattern match and get groups of Strings.

PS: I checked JDK 8, 11 and 17, behavior seems to be consistent for a while now.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!