gpt4 book ai didi

Scala:什么是::in { case x::y::_ => y}?方法还是案例类?

转载 作者:行者123 更新时间:2023-12-05 01:20:05 24 4
gpt4 key购买 nike

object Test1 extends App {
val list: List[Int] => Int = {
case x :: y :: _ => y //what is ::? method or case class?
}
println(list(List(1, 2, 3))) //result is 2.
}

我在 scala IDE 中设置了“语法着色”,方法 的前景色我设置为红色。代码截图: enter image description here而且我无法打开black::的声明,所以我不知道它是什么。

如果black::是方法,应该这样调用:

... {case _.::(y).::(x) => y}     //compile failed!

那么,什么是black::?方法还是案例类?

非常感谢!

最佳答案

我认为这是描述的方法 here .为了历史的缘故,以防该页面消失,这里是简介:

About pattern matching on Lists

If you review the possible forms of patterns explained in Chapter 15, you might find that neither List(...) nor :: looks like it fits one of the kinds of patterns defined there. In fact, List(...) is an instance of a library-defined extractor pattern. Such patterns will be treated in Chapter 24. The "cons" pattern x :: xs is a special case of an infix operation pattern. You know already that, when seen as an expression, an infix operation is equivalent to a method call. For patterns, the rules are different: When seen as a pattern, an infix operation such as p op q is equivalent to op(p, q). That is, the infix operator op is treated as a constructor pattern. In particular, a cons pattern such as x :: xs is treated as ::(x, xs). This hints that there should be a class named :: that corresponds to the pattern constructor. Indeed there is such as class. It is named scala.:: and is exactly the class that builds non-empty lists. So :: exists twice in Scala, once as a name of a class in package scala, and again as a method in class List. The effect of the method :: is to produce an instance of the class scala.::. You'll find out more details about how the List class is implemented in Chapter 22.

所以它是 scala.::(a,b)

关于Scala:什么是::in { case x::y::_ => y}?方法还是案例类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34625063/

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