Scala:缺少参数类型
发布时间:2020-12-16 09:10:55 所属栏目:安全 来源:网络整理
导读:我在 Scala-REPL中键入以下内容: scala List(1,2,3).toSet.subsets(2).map(_.toList)res0: Iterator[List[Int]] = non-empty iteratorscala List(1,3).toSet.subsets.map(_.toList)console:8: error: missing parameter type for expanded function ((x$1)
我在
Scala-REPL中键入以下内容:
scala> List(1,2,3).toSet.subsets(2).map(_.toList) res0: Iterator[List[Int]] = non-empty iterator scala> List(1,3).toSet.subsets.map(_.toList) <console>:8: error: missing parameter type for expanded function ((x$1) => x$1.toList) List(1,3).toSet.subsets.map(_.toList) 为什么我得到第二行的错误?这是编译器中的错误还是我错过了什么? 解决方法
矛盾的是,第一个版本的作用是因为应用程序子集(2)中的子集比没有括号更加模糊.
因为方法是重载的,所以在应用程序中,编译器暂停求解toSet的B结果,并决定B是Int.所以它知道地图的param类型是什么样的. 在没有括号的版本中,具有参数列表的方法不是候选项,因为没有触发eta扩展.所以当它打印地图应用程序时,它没有得出关于B的结论,这是映射函数的输入类型. 简单的解决办法是告诉它推导出B: trait Test { def f1 = List(1,3).to[Set].subsets.map(_.toList) // instead of .toSet def f2 = List(1,3).toSet.subsets(2).map(_.toList) } 原始代码上的-Ytyper-debug的输出显示了重载分辨率如何类型推断: | | | | | | -> => Iterator[scala.collection.immutable.Set[B]] <and> (len: Int)Iterator[scala.collection.immutable.Set[B]] | | | | | solving for (B: ?B) | | | | | |-- 2 : pt=Int BYVALmode-EXPRmode-POLYmode (silent: method f2 in Test) | | | | | | -> Int(2) | | | | | solving for (B: ?B) | | | | | -> Iterator[scala.collection.immutable.Set[Int]] 另一种解决方法是通过扩展方法: scala> implicit class ss[A](val s: Set[A]) { def ss(n: Int) = s subsets n ; def ss = s.subsets } defined class ss scala> List(1,3).toSet.ss.map(_.toList) res1: Iterator[List[Int]] = non-empty iterator 看看他们是否会改变图书馆: https://github.com/scala/scala/pull/4270 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |