【发布时间】:2014-01-14 03:49:02
【问题描述】:
鉴于此 RichFile 类及其伴随对象:
class RichFile(filePath: String) {
val file = new File(filePath)
}
object RichFile {
def apply(filePath: String) = new RichFile(filePath)
def unapply(rf: RichFile) = {
if (rf == null || rf.file.getAbsolutePath().length() == 0)
None
else {
val basename = rf.file.getName()
val dirname = rf.file.getParent()
val ei = basename.indexOf(".")
if (ei >= 0) {
Some((dirname, basename.substring(0, ei), basename.substring(ei + 1)))
} else {
Some((dirname, basename, ""))
}
}
}
def unapplySeq(rf: RichFile): Option[Seq[String]] = {
val filePath = rf.file.getAbsolutePath()
if (filePath.length() == 0)
None
else
Some(filePath.split("/"))
}
}
基本上我想将文件路径的所有组件提取为一个序列。为什么通配符匹配在以下代码中不起作用?特别是第一个case 语句我收到错误star patterns must correspond with varargs parameters。
val l = List(
RichFile("/abc/def/name.txt"),
RichFile("/home/cay/name.txt"),
RichFile("/a/b/c/d/e"))
l.foreach { f =>
f match {
case RichFile(_*) => println((x, y))
case RichFile(a, b, c) => println((a, b, c))
}
}
我也想匹配它们,就像我们匹配 Scala 中的列表一样,如下所示:
l.foreach { f =>
f match {
case a::b::"def"::tail => println((a, tail))
case RichFile(_*) => println((x, y))
case RichFile(a, b, c) => println((a, b, c))
}
}
如何使用unapplySeq 做到这一点?
【问题讨论】:
标签: scala