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?

Ian McGrath
  • 982
  • 2
  • 10
  • 23
  • 1
    `val p = scala.math.min _` – dmitry May 01 '17 at 08: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 ? – Ian McGrath May 01 '17 at 08: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 :) http://stackoverflow.com/questions/8000903/what-are-all-the-uses-of-an-underscore-in-scala – Tanjin May 01 '17 at 08:48

2 Answers2

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.

Tanjin
  • 2,442
  • 1
  • 13
  • 20
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.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487