Avoiding boxing/unboxing within function

后端 未结 3 1840
[愿得一人]
[愿得一人] 2021-02-01 08:48

For a numeric intensive code I have written a function with the following signature:

def update( f: (Int,Int,Double) => Double ): Unit = {...}
3条回答
  •  野性不改
    2021-02-01 09:26

    As Function1 is specialized, a possible solution is to use currying and change your update method to:

    def update( f: Int => Int => Double => Double ): Unit = {...}
    

    and change the inlined function accordingly. with your example (update was slightly modified to test it quickly):

    scala> def update( f: Int => Int => Double => Double ): Double = f(1)(2)(3.0)
    update: (f: Int => (Int => (Double => Double)))Double
    
    scala> update(i => j => _ => if (i == 0 && j == 0) 1.0 else 0.5)
    res1: Double = 0.5
    

    Edit: Ase explained in the comments, it doesn't completely help since the first parameter is still boxed. I leave the answer to keep a trace about it.

提交回复
热议问题