Home > Software design >  the short-written rules of using "_" in scala anonymous function confused me
the short-written rules of using "_" in scala anonymous function confused me

Time:10-30

I have two kinds of definition of a three-parameter function as below:

val minus1: (Int, Int, Int) => Int = _ - _ - _
val minus2: (Int, Int, Int) => Int = (_ - _) - _

minus1 is fine, but minus2 is reported illegal, that confused me a lot

Following ComDubh's insturction, i write a new function like:

val minus3 : (Int, Int, Int)=>Int = ((_-_)-_)

why this was still wrong? Did that mean i shouldn't put any parenthese between the "_"s? and i have a more complicated question like

val func4: Int=>Int = x => if (x>0) 1 else -1
val func5: Int=>Int = if (_>0) 1 else -1

func4 is good, but why i can't omit the parametr name "x" to rewrite the function as func5(the compiler regards the 1 or -1 as the return value and reports Int(1) doesn't fit Int=>Int). Thans for your time

CodePudding user response:

You're creating an anonymous function. Scala has to know where the definition of the anonymous function starts and ends. Your use of parentheses in minus2 tells Scala that _ - _ is the complete function. The compiler isn't happy of course as you're missing an argument.

  • Related