为什么 sortWith(lt: (A, A) => Boolean) 需要一个有两个参数的函数,但可以使用只有一个参数的 compareTo?

Why sortWith(lt: (A, A) => Boolean) require a function with two params but can use compareTo which have only one param?

https://www.scala-lang.org/api/current/scala/collection/immutable/List.html#sortWith(lt:(A,A)=%3EBoolean) :

List("Steve", "Tom", "John", "Bob").sortWith(_.compareTo(_) < 0) = List("Bob", "John", "Steve", "Tom")

sortWith 参数为:

lt: (A, A) => Boolean

其中一个函数有两个参数和 return 一个布尔值

但是 compareTo 只有一个参数:

def compareTo(that: A): Int

如果 compareTo 是一个函数,它有两个 params.but 它是 scala,所以 compareTo 是一个方法,它只有一个参数

那为什么sortWith中可以使用compareTo?好像不符合sortWith的类型签名

这种下划线的用法被称为Placeholder Syntax for Anonymous Functions:

Such an expression represents an anonymous function where subsequent occurrences of underscores denote successive parameters.

注意每个下划线代表不同的参数,例如

_ + _

扩展到

(x1, x2) => x1 + x2

另外表达式 _ + _ 使用无点语法而不是

_.+(_)

例如

List("Steve", "Tom", "John", "Bob").reduce((x1: String, x2: String) => x1.+(x2)) // : String = "SteveTomJohnBob"
List("Steve", "Tom", "John", "Bob").reduce((x1, x2) => x1.+(x2)) // : String = "SteveTomJohnBob"
List("Steve", "Tom", "John", "Bob").reduce(_.+(_)) // : String = "SteveTomJohnBob"
List("Steve", "Tom", "John", "Bob").reduce(_ + _) // : String = "SteveTomJohnBob"

所以现在应该更清楚为什么表达式 _.compareTo(_) < 0 起作用了

List("Steve", "Tom", "John", "Bob").sortWith(_.compareTo(_) < 0) // : List[String] = List("Bob", "John", "Steve", "Tom")
List("Steve", "Tom", "John", "Bob").sortWith((x1, x2) => x1.compareTo(x2) < 0) // : List[String] = List("Bob", "John", "Steve", "Tom")

另一种看待这个问题的方式让我们输入加糖表达式

scala> (_.compareTo(_) < 0): ((String, String) => Boolean)
val res0: (String, String) => Boolean = $Lambda65/418832725@18987bf5