1

I'm new to Scala but I've been working with Java for a long time now so programming is not new to me. Anyway I read a some books on Scala and came across an example that a method returns a function. Now returning a function from method is not new since Java 8 support lambda expression but I can't understand the following example:

def lowIt(inputValue: String): Double => Double = {
  if (inputValue == "Lower") x => x * 0.85
  else x => x
}

I don't understand where x comes from, I would expect the following:

def lowIt(inputValue: String): Double => Double = x => {
   if (inputValue == "Lower") x * 0.85
  else x
}

I don't get the first way of writing the above method. Thank u in advance

2 Answers 2

2

If it seems more intuitive to you, you could start with the second version: it behaves the same as the first one. However, if you look at it closely, you will notice that the inputValue captured by the closure never changes, so that your function

x => { if (inputValue == "Lower") x * 0.85 else x }

always takes either the then-branch, or the else-branch. But then you don't really have to make the if-else comparison for every single x. Instead, you can make the decision just once.

In case that inputValue == "Lower" holds, your function becomes

x => { if (true) x * 0.85 else x } 
x => x * 0.85
_ * 0.85

In the case that inputValue != "Lower", your function is just

x => { if (false) x * 0.85 else x }
x => x
identity

Thus, starting with your own version, after a few simple rewriting steps, the function is simplified to

def lowIt(inputValue: String): Double => Double = {
  if (inputValue == "Lower") x => x * 0.85
  else x => x
}

or even shorter:

def lowIt(inputValue: String): Double => Double = {
  if (inputValue == "Lower") _ * 0.85
  else identity
}

The rewritten versions are more efficient, because the if does not have to be evaluated every time. The last version might even be a bit clearer, because the identity-function is written down as one non-simplifiable "thing" that can be returned.

Sign up to request clarification or add additional context in comments.

Comments

1

you can rewrite that function like this:

def lowIt(inputValue: String): Double => Double = {
  if (inputValue == "Lower") {(x: Double) => x * 0.85 }
  else {(x: Double) => x}
}

the 2 return values are functions, and x is the input of the function

1 Comment

you can replace {(x: Double) => x} with identity

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.