0

I want to assign an existing function to a variable. According to this site, it is as easy as:

val p = scala.math.pow(_, _)
pow: (Double, Double) => Double = <function2>

but when I try to do the same thing in my code it does not work.

def main(args: Array[String]) = {
    val p = scala.math.min(_, _)
    val func = if ( args(0).equalsIgnoreCase("min"))  math.min(_,_) else math.max(_,_)
}

I thought this maybe due to use of if and else condition in same line, but I get error when assigning value to variable p as well.

Error I get:

missing parameter type for expanded function ((x$1, x$2) => scala.math.min(x$1, x$2))

Why does it not work for me and how can I fix it?

3
  • 1
    val p = scala.math.min _ Commented May 1, 2017 at 8:32
  • @dmitry Why does pow need 2 underscores and min and max will do with just 1? i.e. how do you know if 1 underscore is sufficient ? Commented May 1, 2017 at 8:38
  • I'd recommend reading the top voted answer here, specifically the ending segment. Also scala.math.pow _ single underscore works just as well. The short answer to knowing what is sufficient is to see if it compiles successfully :) stackoverflow.com/questions/8000903/… Commented May 1, 2017 at 8:48

2 Answers 2

2

The type parameters must be defined for your func:

val func: (Int, Int) => Int = if (args.head.equalsIgnoreCase("min"))  math.min(_,_) else math.max(_,_)

Alternatively as user dmitry pointed out, use a single underscore:

val func = if (args.head.equalsIgnoreCase("min"))  math.min _ else math.max _

However it seems like you are a beginner to the language - personally I would practice explicitly stating the types of interest like in the first example until you have a better handle on things.

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

Comments

1

There is just a single scala.math.pow method, but there are multiple overloads of min and max: def min(x: Double, y: Double): Double, def min(x: Int, y: Int): Int etc. Without providing expected argument type, Scala can't know which one you mean. I'd write e.g. val p = scala.math.min(_: Int, _: Int) or val p = scala.math.min(_: Double, _: Double) (or you can specify the type of p directly as in Tanjin's answer).

val p = min _ happens to work because the min(x: Int, y: Int) overload is the most specific one, but I think it's a bad idea to rely on it when starting.

Comments

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.