tech_human
tech_human

Reputation: 7100

Function as parameter Kotlin

I wish to replace some part of the string using some other string found with the help of regex. For generating the replacement string, I have to write a function. Below is my string in which I want to replace "{#string}" with something else.

var testString = "https://www.google.com/solution?region={america}&&country={usa}&&language={english}"

For testing purposes, I tried the below which works fine:

testString = testString.replace(regex, "")

But instead of "", I would like to have a block or function there which generates a replacement string based on the keys i.e. region, country and language and returns it. Below is what I tried and the error I am getting. What am I missing syntactically?

testString = testString.replace(regex, fun() : String {
    return ""
}) 

Error:

enter image description here

Upvotes: 0

Views: 315

Answers (2)

Willi Mentzel
Willi Mentzel

Reputation: 29844

The signature of the anonymous function you pass to replace is wrong. As the error message states the function needs to be of type (MatchResult) -> CharSequence.

This would work since String is a subclass of CharSequence:

val result = "Some String".replace(Regex("[S]"), fun(mr: MatchResult) : String {
    return "s"
}) // result will be "some string"

Note: Instead of the anonymous function, you could also use a lambda which can infer the parameter and return type:

val result = "Some String".replace(Regex("[S]")) {
    "s"
} 

The MatchResult will be available as it then.

Upvotes: 1

Luciano Ferruzzi
Luciano Ferruzzi

Reputation: 1102

This should work:

string.replace(regex) { /*do your logic here*/ }

You can also access the match result with the function, and it should return a CharSequence:

string.replace(regex) { matchResult -> "" }

Or reference a declared function

string.replace(regex, ::doMagic)

fun doMagic(matchResult: MatchResult): CharSequence {
    /*
     *some cool stuff
     */
    return ""
 }

Upvotes: 0

Related Questions