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

Viewed 1532

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(..)?

3 Answers

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

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.

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.

Related