scala, Passing an operator as argument of a function

前端 未结 3 919
说谎
说谎 2021-02-20 08:06

I have this code:

for( i <- 0 to 8){
  ((numbers(i) - i)/3).abs + ((numbers(i) - i)%3).abs
}

and I would like to do, as the title says, some

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-20 08:17

    First, you need to correctly define op as a function (specifically, a Function2)

    def operate(a: Int, b: Int, op: (Int, Int) => Int ) : Int = (op ((a - b), 3)).abs

    Operators in Scala are actually methods: + is a method of Int(and Long, Double, ...) in Scala OO foundation. Then, to pass a operator (method) as a function, you can lift it using the underscore notation: operate(5, 3, _ + _)

提交回复
热议问题