Lucian Enache
Lucian Enache

Reputation: 2520

Spray routing filter path parameter

given this snippet of code

 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)
  }

}

}

How could I replace the if-else with a match-case pattern, eventually using also an Option object with Some-None.

My aim is to filter out the length and handle the case where length is an Int exists , it does not exist, is something else than an Int.

I have tried this but it does not work.

 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") ???
  }
}

}

Upvotes: 0

Views: 181

Answers (1)

Kulu Limpa
Kulu Limpa

Reputation: 3541

My guess is that in your non-working code, length is still an Int, and hence does not match with either Some or None. If you wanted to translate your if-else code to a match-statement, I'd suggest something similar to the following code, which matches for positive Int values:

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

If you want to be fancy, you can also define a custom extractor:

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")
}

And if you somehow do have Option values, the following should work:

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")
}

All of those snippets print

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

Upvotes: 1

Related Questions