此代码编译:
def wtf(arg: Any) = {
arg match {
case Nil => "Nil was passed to arg"
case List() => "List() was passed to arg"
case _ =>"otherwise"
}
}
Run Code Online (Sandbox Code Playgroud)
但是这个没有:
def wtf(arg: Any) = {
arg match {
case List() => "List() was passed to arg"
case Nil => "Nil was passed to arg"
case _ =>"otherwise"
}
}
Run Code Online (Sandbox Code Playgroud)
行 情况Nil => ...被标记为无法访问的代码.为什么,在第一种情况下,行案例List()=> ...没有标记相同的错误?
从电子邮件列表中我得到2个值:
在scala中对此进行编码的惯用方法是什么?到目前为止,我有:
val primaryEmail = emails.headOption
val conf = Map[String, Any](
"email" -> primaryEmail,
"additionalEmails" ->
primaryEmail.map(_ => emails.tail).getOrElse(List())
)
Run Code Online (Sandbox Code Playgroud)
编辑:至于为什么有Any:我们使用GSON进行json序列化,并在内部将所有集合转换为java集合并将它们传递给jsonSerializationContext.serialize,它们将java.lang.Object作为参数,所以很Any适合我们.
是否有理由match反对Seq在IndexedSeq类型上使用不同于对类型的处理方式LinearSeq?对我来说,无论输入类型如何,下面的代码似乎应该完全相同.当然它不会或我不会问.
import collection.immutable.LinearSeq
object vectorMatch {
def main(args: Array[String]) {
doIt(Seq(1,2,3,4,7), Seq(1,4,6,9))
doIt(List(1,2,3,4,7), List(1,4,6,9))
doIt(LinearSeq(1,2,3,4,7), LinearSeq(1,4,6,9))
doIt(IndexedSeq(1,2,3,4,7), IndexedSeq(1,4,6,9))
doIt(Vector(1,2,3,4,7), Vector(1,4,6,9))
}
def doIt(a: Seq[Long], b: Seq[Long]) {
try {
println("OK! " + m(a, b))
}
catch {
case ex: Exception => println("m(%s, %s) failed with %s".format(a, b, ex))
}
}
@annotation.tailrec
def m(a: Seq[Long], b: Seq[Long]): Seq[Long] = {
a match {
case Nil => b
case firstA :: moreA => b …Run Code Online (Sandbox Code Playgroud)