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

android - net_scheduler holding wakelock -

sql - MySQL : Getting Entries from a many-to-many table -

java - Retrieving data from database using jsp (Hibernate + Spring + Maven) -