Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 函数作为参数Kotlin_String_Kotlin_Replace - Fatal编程技术网

String 函数作为参数Kotlin

String 函数作为参数Kotlin,string,kotlin,replace,String,Kotlin,Replace,我希望使用在regex帮助下找到的其他字符串替换字符串的某些部分。为了生成替换字符串,我必须编写一个函数。下面是我的字符串,我想用其他内容替换{string} var testString = "https://www.google.com/solution?region={america}&&country={usa}&&language={english}" 出于测试目的,我尝试了以下方法,效果良好: testString = testString.repl

我希望使用在regex帮助下找到的其他字符串替换字符串的某些部分。为了生成替换字符串,我必须编写一个函数。下面是我的字符串,我想用其他内容替换{string}

var testString = "https://www.google.com/solution?region={america}&&country={usa}&&language={english}"
出于测试目的,我尝试了以下方法,效果良好:

testString = testString.replace(regex, "")
但是,我希望在那里有一个块或函数,它根据关键字(即地区、国家和语言)生成替换字符串并返回它。下面是我尝试过的和我得到的错误。我在语法上遗漏了什么

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

这应该起作用:

string.replace(regex) { /*do your logic here*/ }
您还可以使用函数访问匹配结果,它应该返回CharSequence:

string.replace(regex) { matchResult -> "" }
或引用声明的函数

string.replace(regex, ::doMagic)

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

传递给替换的匿名函数的签名错误。正如错误消息所述,函数的类型必须为MatchResult->CharSequence

这将起作用,因为String是CharSequence的子类:

string.replace(regex) { matchResult -> "" }
注意:除了匿名函数,您还可以使用lambda来推断参数和返回类型:

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

MatchResult届时将可用。

我不知道Kotlin,因此放弃了尝试,但当我在上尝试时,它对我无效。@tevemadar替换重载的第一个参数必须是正则表达式而不是字符串。我编辑了我的答案,使之更清楚。谢谢。这就是为什么我不应该检查手机上的新东西——尽管我试图阅读错误信息并检查了错误,但我完全没有注意到这个细节。