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

741
Views
Kotlin: ¿Cómo llamar a un método con el mismo nombre en una extensión?

He escrito una startsWith(substring) que también es aplicable a cadenas anulables. Desafortunadamente, mi implementación da como resultado un StackOverflowError porque la extensión se llama a sí misma y no al String.startsWith(..) .

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

¿Es posible llamar a String.startsWith(..) ?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Puede usar la import as sintaxis para importar explícitamente el método startsWith de la biblioteca estándar con un nombre diferente que luego puede usar sin conflicto:

 import kotlin.text.startsWith as ktStartsWith private fun String?.startsWith(sub: String): Boolean = this?.ktStartsWith(sub) == true
over 4 years ago · Santiago Trujillo Report

0

Puedes escribirlo así:

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

que usa esta firma de startsWith de StringsJVM.kt :

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

De esta manera, al pasar explícitamente un valor al parámetro ignoreCase ,
evita la recursividad porque su función de extensión ya no se llama a sí misma.

over 4 years ago · Santiago Trujillo Report

0

Primero debe hacer la verificación nula, luego llamar a startsWith a la String no nula. Aquí hay un ejemplo usando run :

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

Dentro del bloque this?.run{ /* this is non-null inside here */} . Por lo tanto, llamar a startsWith inside no llamará a su propio método de extensión.

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!