中缀运算符上的Scala匹配分解 [英] Scala match decomposition on infix operator

查看:83
本文介绍了中缀运算符上的Scala匹配分解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解Scala中List的实现.特别是,我试图弄清楚如何使用infix运算符编写匹配表达式,例如:

I'm trying to understand the implementation of Lists in Scala. In particular I'm trying to get my head around how you can write match expressions using an infix operator, for example:

a match {
  case Nil => "An empty list"
  case x :: Nil => "A list without a tail"
  case x :: xs => "A list with a tail"
}

如何将匹配表达式设为x :: xs而不是List(x, xs)?

How is the match expression allowed to be x :: xs rather than List(x, xs)?

推荐答案

Jay Conrad的答案几乎是正确的.重要的是,某处有一个名为::的对象,该对象实现了unapply方法,返回类型为Option[(A, List[A])].因此:

Jay Conrad's answer is almost right. The important thing is that somewhere there is an object named :: which implements the unapply method, returning type Option[(A, List[A])]. Thusly:

object :: {
  def unapply[A](ls: List[A]): Option[(A, A)] = {
    if (ls.empty) None
    else Some((ls.head, ls.tail))
  }
}

// case objects get unapply for free
case object Nil extends List[Nothing]

::List的情况下,此对象恰巧是由于::是扩展List特性的案例类而产生的.但是,如上面的示例所示,根本没有是案例类.

In the case of :: and List, this object happens to come out of the fact that :: is a case class which extends the List trait. However, as the above example shows, it doesn't have to be a case class at all.

这篇关于中缀运算符上的Scala匹配分解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆