How do I implement a generic mathematical function in Scala

后端 未结 2 766
南旧
南旧 2020-12-23 14:30

I\'m just getting started with Scala and something which I think should be easy is hard to figure out. I am trying to implement the following function:

def squ

2条回答
  •  清歌不尽
    2020-12-23 15:08

    You can define square as:

    def square[T: Numeric](x: T): T = implicitly[Numeric[T]].times(x,x)
    

    This approach has the advantage that it will work for any type T that has an implicit conversion to Numeric[T] (i.e. Int, Float, Double, Char, BigInt, ..., or any type for which you supply an implicit conversion).

    Edit: Unfortunately, you'll run into trouble if you try something like List(1,2,3).map(square) (specifically, you'll get a compile error like "could not find implicit value for evidence parameter of type Numeric[T]". To avoid this issue, you can overload square to return a function:

    object MyMath {
       def square[T: Numeric](x: T) = implicitly[Numeric[T]].times(x,x)
       def square[T: Numeric]: T => T = square(_)
    }
    

    Hopefully someone with a better understanding of the type inferencer will explain why that is.

    Alternatively, one can call List(1,2,3).map(square(_)), as Derek Williams pointed out in the scala-user mailing list thread.

提交回复
热议问题