Passing functions for all applicable types around

前端 未结 4 1531
广开言路
广开言路 2021-01-05 14:02

I followed the advice found here to define a function called square, and then tried to pass it to a function called twice. The functions are defined like this:



        
4条回答
  •  日久生厌
    2021-01-05 14:43

    Another solution is to lift square into partially applied function:

    scala> twice(square(_:Int),2)
    res1: Int = 16
    

    This way the implicit is applied to square as in:

    scala> twice(square(_:Int)(implicitly[Numeric[Int]]),2)
    res3: Int = 16
    

    There is even another approach:

    def twice[T:Numeric](f: (T) => T, a: T): T = f(f(a))
    scala> twice[Int](square,2)
    res1: Int = 16
    

    But again, the type parameter don't get inferred.

提交回复
热议问题