列表 – 中缀运算符上的Scala匹配分解
发布时间:2020-12-16 19:04:36 所属栏目:安全 来源:网络整理
导读:我正在试图了解 Scala中列表的实现.特别是我试图让我的头脑如何使用中缀运算符写匹配表达式,例如: 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而不是Lis
我正在试图了解
Scala中列表的实现.特别是我试图让我的头脑如何使用中缀运算符写匹配表达式,例如:
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)? 解决方法
杰·康拉德的回答是对的.重要的是,某个地方有一个名为::的实现unapply方法的对象,返回类型为Option [(A,List [A])].正是如此:
object :: { def unapply[A](ls: List[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特征的case类.然而,如上例所示,它根本不一定是一个case类. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |