scala高阶函数类型推断什么时候失效?

class TypeInfer(self: Int, other: Int) {
  def test(num: Int, word: String, fun1: (Int, Int) => Int): Unit = {
    fun1(self, other)
  }

  def test(word: String, num: Int, fun1: (Int, Int) => Int): Unit = {
    fun1(self, other)
  }

  def test1(num: String, word: Int, fun1: Int): Unit = {
    fun1(self, other)
  }

  def test1(num: Int, word: String, fun1: Int): Unit = {
    fun1(self, other)
  }
}

这段代码中的test()函数是有重载的,且以高阶函数为参数。当我们调用的时候必须指明高阶函数的参数类型。

 

1  def main(args: Array[String]): Unit = {
2     val num1:Int = 1
3     val num2:Int = 1
4     val num3:Int = 1
5     val infer = new TypeInfer(num1:Int,num2:Int)
6     infer.test(num3,"hi",(x:Int, y:Int)=>x+y)
7     //infer.test(num3,"hi",(x, y)=>x+y)
8     infer.test1(1,"a",1)
9   }

第6行是正确的,可以编译通过,但是第7行被注释的代码是不能编译通过的,也就是说这里类型推断失效了。经过测试发现,当有重载函数,且参数个数相同,且高阶函数所处的位置一样时,这时高阶函数类型推断会失效,在调用重载函数的时候必须像上述代码第6行那样显示指明高阶函数的类型。这是可以看出语法上是没有歧义的,按照正常思维是可以推断出高阶函数的类型的,但是为什么scala编译器不能做到呢?是bug?还是另有考虑?

posted on 2018-03-05 17:50  skyer1992  阅读(198)  评论(0编辑  收藏  举报

导航