zoukankan      html  css  js  c++  java
  • 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?还是另有考虑?

  • 相关阅读:
    备份
    Ibatis_dataMapper
    查询成绩都大于80分的学生
    删除文件的工具
    从运行中启动收索引擎
    数据库Northwind
    搭建Android开发环境
    数据库知识结构
    数据库MedicineMis_STD
    数据库work
  • 原文地址:https://www.cnblogs.com/yuanyifei1/p/8510369.html
Copyright © 2011-2022 走看看