reducing an Array of Float using scala.math.max

前端 未结 4 1900
温柔的废话
温柔的废话 2021-01-06 09:53

I am confused by the following behavior - why does reducing an Array of Int work using math.max, but an Array of Float requires a wrapped function? I have memories that this

4条回答
  •  醉酒成梦
    2021-01-06 10:03

    It doesn't seem to be a bug. Consider the following code:

    class C1 {}
    
    object C1 {
      implicit def c2toc1(x: C2): C1 = new C1
    }
    
    class C2 {}
    
    class C3 {
      def f(x: C1): Int = 1
      def f(x: C2): Int = 2
    }
    
    (new C3).f _                                    //> ... .C2 => Int = 
    

    If I remove implicit conversion I will get an error "ambiguous reference". And because Int has an implicit conversion to Float Scala tries to find the most specific type for min, which is (Int, Int) => Int. The closest common superclass for Int and Float is AnyVal, that's why you see (AnyVal, AnyVal) => AnyVal.

    The reason why (x, y) => min(x, y) works is probably because eta-expansion is done before type inference and reduce has to deal with (Int, Int) => Int which will be converted to (AnyVal, AnyVal) => AnyVal.

    UPDATE: Meanwhile (new C3).f(_) will fail with "missing parameter type" error, which means f(_) depends on type inference and doesn't consider implicit conversions while f _ doesn't need parameter type and will expand to the most specific argument type if Scala can find one.

提交回复
热议问题