Reputation: 795
On an Android project with both Kotlin and java, I want to use the Kotlin functions substringBeforeLast(delimiter)
and substringAfterLast(delimiter)
in some java files.
So i thought of using extensions. I did the following which works,
fun String.getStringAfterLast(): String{
return this.substringAfterLast(".")
}
however i was thinking of passing the delimiter as a parameter, but it gives me an error when trying to use in java "remove 2nd argument..."
fun String.getStringBeforeLast(delimiter: String): String{
return this.substringBeforeLast(delimiter)
}
Is the approach correct ? Can it be done ?
Upvotes: 0
Views: 942
Reputation: 28472
Your approach to this problem is correct and it should work. For example, with this Kotlin code:
fun String.getStringBeforeLast(delimiter: String): String{
return this.substringBeforeLast(delimiter)
}
You should be able to invoke the function from Java like this:
ExtensionKt.getStringBeforeLast(str, ",");
If it didn't work then I guess there had to be some small mistake, like for example: you added delimiter
param to getStringBeforeLast()
function, but mistakenely tried to invoke getStringAfterLast()
function from Java.
Also, you can always invoke functions of Kotlin stdlib directly from Java. Just note that substringBeforeLast()
/substringAfterLast()
actually receive one additional, optional parameter and you need to provide it from Java, making the code a little more verbose:
StringsKt.substringBeforeLast(str, ",", str);
Upvotes: 1