模式匹配是否创建一个函数?



根据doc: List.sortWith方法有签名

def sortWith(lt: (A, A) ⇒ Boolean): List[A]

对于字符串列表,我们可以这样做:

myList.sortWith((_,_) match { case(s1: String, s2: String) => s1.compareTo(s2)}

。当scala说它需要一个函数类型时,我们使用模式匹配。

在这种情况下,我们是否可以说

(_,_) match { case(s1: String, s2: String) => s1.compareTo(s2)

是下列函数类型(A, A) ⇒ Boolean的函数应用?

注意,compareTo返回一个Integer。如果您希望遵循(A, A) ⇒ Boolean签名,对于字母升序,您可以使用<

所有这三个匿名函数将对List进行排序:

myList.sortWith(_ < _)
myList.sortWith { case(a, b) => a < b }
myList.sortWith( (_, _) match { case (a, b) => a < b} )

最新更新