Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

742
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda