喷路由过滤路径参数

Spray routing filter path parameter

给定这段代码

 val passRoute = (path("passgen" / IntNumber) & get) { length =>
complete {
  if(length > 0){
    logger.debug(s"new password generated of length $length")
    newPass(length)
  }
  else {
    logger.debug("using default length 8 when no length specified")
    newPass(8)
  }

}

}

我如何用匹配案例模式替换 if-else,最终还使用带有 Some-None 的 Option 对象。

我的目标是过滤掉长度并处理长度是 Int 存在,它不存在,不是 Int 的情况。

我已经试过了,但是没有用。

 val passRoute = (path("passgen" / IntNumber) & get) { length =>
complete {
  length match {
     case Some(match: Int) => print("Is an int")
     case None => print("length is missing")
     //missing the case for handling non int but existent values
     // can be case _ => print("non int") ???
  }
}

}

我的猜测是,在您的非工作代码中,length 仍然是一个 Int,因此与 SomeNone 都不匹配。如果您想将 if-else 代码转换为 match 语句,我建议您使用类似于以下代码的代码,它匹配正 Int 值:

List(10, -1, 3, "hello", 0, -2) foreach {
  case length: Int if length > 0 => println("Found length " + length)
  case _ => println("Length is missing")
}

如果你想花哨,你也可以定义一个自定义提取器:

object Positive {
  def unapply(i: Int): Option[Int] = if (i > 0) Some(i) else None
}

List(10, -1, 3, "hello", 0, -2) foreach {
  case Positive(length) => println("Found length " + length)
  case _ => println("Length is missing")
}

如果您确实有 Option 值,则以下内容应该有效:

List(10, -1, 3, "hello", 0, -2) map (Some(_)) foreach {
  case Some(length: Int) if length > 0 => println("Found length " + length)
  case _ => println("Length is missing")
}

所有这些片段打印

Found length 10
Length is missing
Found length 3
Length is missing
Length is missing
Length is missing