0
votes

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("-")
  }
1
Can you please elaborate what do you mean by high order function? Do you want a function that creates the getData function?Tomer Shetah
Yes. By any means i want to avoid this if else conditions like: def getData = (f: String => String, value: String) and then i can pass either substring or concat. I want this method to be as precise as possible @TomerShetahAvenger
Or def getData(value: String) : String => StringAvenger
So there is no better way to write this function ?Avenger
@EatPayBong I think you should figure out what problem you are trying to solve instead of just trying to write a HOFA-Developer-Has-No-Name

1 Answers

2
votes

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.