Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

479
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda