Reputation: 877
I have these two functions:
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("-")
}
I want to convert them to higher order functions.
I have tried this so far. What would be the higher order function for it?
def getData = (value: String) => {
val res = replaceValue(value).replace("-", ":")
val res1 = res.lastIndexOf(":")
if (res1 != -1) res.substring(0,3)
else res.concat("-")
}
Upvotes: 0
Views: 83
Reputation: 8529
You can do the following:
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)
}
}
Code run can be found at Scastie.
Upvotes: 2