scala - Extractor with pattern matching -


this scala code

object twice {   def apply(x: int): int = x * 2   def unapply(z: int): option[int] = if (z%2 == 0) some(z/2) else none }  object twicetest extends app {   val x = twice(5)   println(x)   x match { case twice(n) => println(n) } } 

prints

10 5 

when twicetest run. question is: x integer , not function twice(n), why pattern matching works?

it's because of pattern matching expression.

let's take @ it:

x match {   case twice(n) => println(n) } 

you matching using twice. in background, call twice.unapply() parameter x. if result some(foo), substitute value of foo value of n. otherwise won't match.

see this longer explanation.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -