使用::for 列表的 scala 匹配案例

标签 scala

鉴于此模式匹配:

List(1,2,3) match {
  case head :: tail => println(">>> head=" + head)
}

我假设 '::' 是在 scala.collection.immutable 中找到的 case 类,但是如何允许以这种形式(中缀表示法)写入 '::'? - 是否有特定规则允许这样做?

谢谢

最佳答案

你甚至可以写:

val head :: tail = List(1, 2, 3)

基本上任何需要模式的东西(赋值、match 语句或 for-comprehension 中的一行)都可以采用提取器,它被定义为具有 unapply 的实体。方法。

scala 为您提供的语法糖之一是;如果您有提取器 X(a, b) ,这可以写成 a X b .这是一个案例类的例子(有一个默认的提取器):
scala> case class X(a: Int, b: String)
defined class X

scala> val a X b = X(1, "two")
a: Int = 1
b: String = two

编写此类实体中缀的能力也扩展到类型:
scala> type MappedTo[A, B] = Map[A, B]
defined type alias MappedTo

scala> def foo(m: Int MappedTo String) = m foreach println
foo: (m: MappedTo[Int,String])Unit

请注意,在这两种情况下,scala 都不会将此类中缀运算符限制为符号标识符

关于使用::for 列表的 scala 匹配案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8665580/

相关文章:

scala - Scala 对象定义中没有父类(super class)名称的 "extends {..}"子句有什么作用?

scala - LinkedHashMap 更改为 HashMap 并在 flink 数据流算子中崩溃

Scala:读取文本文件并过滤值列表

java - Scala 范围、初始化

scala - 英特尔lij : How to indent 2 spaces of next line from beginning of the previous line?

scala - 用简单的界限表达类型不等式条件

scala 组合多个序列

scala - 带 Macwire 的可注入(inject)工厂

scala - 使用 akka-http 执行 OAuth2 身份验证的最佳方法是什么?

arrays - Scala 连接数组并减少值