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

744
Views
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 answers
Answer question

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 Report

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 Report

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 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!