【发布时间】:2021-02-01 05:08:37
【问题描述】:
我有这两个功能:
def replaceValue(value: String): String =
if (value.startsWith(":")) value.replaceFirst(":", "/") else value
def getData(value: String): String = {
val res = replaceValue(value).replace("-", ":")
val res1 = res.lastIndexOf(":")
if (res1 != -1) res.substring(0,3)
else res.concat("-")
}
我想将它们转换为高阶函数。
到目前为止,我已经尝试过了。 它的高阶函数是什么?
def getData = (value: String) => {
val res = replaceValue(value).replace("-", ":")
val res1 = res.lastIndexOf(":")
if (res1 != -1) res.substring(0,3)
else res.concat("-")
}
【问题讨论】:
-
您能否详细说明高阶函数是什么意思?你想要一个创建
getData函数的函数吗? -
是的。无论如何,我想避免这种情况,如果其他条件如下:def getData =(f:String => String,value:String)然后我可以传递子字符串或concat。我希望这种方法尽可能精确@TomerShetah
-
或 def getData(value: String) : String => String
-
那么有没有更好的方法来写这个函数呢?
-
@EatPayBong 我认为您应该弄清楚您要解决的问题,而不是仅仅尝试编写 HOF
标签: scala scala-collections higher-order-functions