gpt4 book ai didi

scala - 在这种情况下,_参数表示什么?

转载 作者:行者123 更新时间:2023-12-04 13:39:23 27 4
gpt4 key购买 nike

下面的方法调用signify中的参数“_”是什么?

这是接受任何类型参数的通配符吗?

val integerSorter = msort[Int]((a, b) => a < b) _

方法msort签名:
  def msort[T](less: (T, T) => Boolean)(xs: List[T]): List[T] = {

最佳答案

解释此问题的最简单方法可能是让编译器完成大部分解释,只需尝试不带下划线的第一行即可:

scala> val integerSorter = msort[Int]((a, b) => a < b)
<console>:11: error: missing arguments for method msort;
follow this method with `_' if you want to treat it as a partially applied function
val integerSorter = msort[Int]((a, b) => a < b)
^

这样就可以了– msort方法具有两个参数列表,但是您仅传递了第一个参数,而尾随的下划线是Scala提供的语法,用于告知编译器在这种情况下需要部分应用程序。

(如果您在REPL中使用下划线尝试该行,则会看到 integerSorter的推断类型为 List[Int] => List[Int],因此要回答第二个问题,不,下划线不允许您提供任何类型的参数。 )

有关更多信息,请参见 the language specification的6.7节:

The expression e _ is well-formed if e is of method type or if e is a call-by-name parameter. If e is a method with parameters, e _ represents e converted to a function type by eta expansion (§6.26.5).



阅读有关eta扩展的部分也可能会有所帮助。

关于scala - 在这种情况下,_参数表示什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23859204/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com