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

750
Vistas
Kotlin: How to call a method with the same name in an extension?

I have written a startsWith(substring) extension that is applicable to nullable strings too. Unfortunatly my implmentation results in a StackOverflowError cause the extension calls it self an not the String.startsWith(..) method.

private fun String?.startsWith(sub: String): Boolean = this?.startsWith(sub)==true

Is is possible to call String.startsWith(..)?

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

You can use the import as syntax to explicitly import the standard library's startsWith method with a different name that you can then use without conflict:

import kotlin.text.startsWith as ktStartsWith

private fun String?.startsWith(sub: String): Boolean = this?.ktStartsWith(sub) == true
over 4 years ago · Santiago Trujillo Denunciar

0

You can write it like this:

private fun String?.startsWith(sub: String): Boolean = this?.startsWith(sub, false) == true

which uses this signature of startsWith from StringsJVM.kt:

public fun String.startsWith(prefix: String, ignoreCase: Boolean = false): Boolean

This way, by explicitly passing a value to the ignoreCase parameter,
you avoid recursion because your extension function does not call itself anymore.

over 4 years ago · Santiago Trujillo Denunciar

0

You should do the null check first, then call startsWith to the non-null String. Here is an example using run:

private fun String?.startsWith(sub: String, ignoreCase: Boolean = false): Boolean = this?.run{startsWith(sub, ignoreCase)} ?: false

Within the block this?.run{ /* this is non-null inside here */}. Therefore, calling startsWith inside will not call your own extension method.

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