我有这两个函数:
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("-")
}发布于 2020-10-18 14:52:29
您可以执行以下操作:
def getDataImpl(f: String => String)(value: String): String = {
f(value)
}
def getDataSubstring: String => String = getDataImpl(_.substring(0,3))
def getDataConcat: String => String = getDataImpl(_.concat("-"))
def getData(value: String): String = {
val replaced = replaceValue(value).replace("-", ":")
if (replaced.contains(":")) {
getDataConcat(replaced)
} else {
getDataSubstring(replaced)
}
}代码运行可以在Scastie上找到。
https://stackoverflow.com/questions/64410139
复制相似问题