Last active
August 29, 2015 14:00
-
-
Save Gab-km/11023107 to your computer and use it in GitHub Desktop.
Scala で Active Patterns っぽいことやってみた
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class FizzBuzzExtractor[T](f: T => Boolean){ | |
def unapply(t: T) = f(t) | |
} | |
val FizzBuzz = new FizzBuzzExtractor[Int](_ % 15 == 0) | |
object Fizz extends FizzBuzzExtractor[Int](_ % 3 == 0) | |
object Buzz extends FizzBuzzExtractor[Int](_ % 5 == 0) | |
object FizzBuzzRunner { | |
def run(num: Int) = num match { | |
case FizzBuzz() => println("FizzBuzz") | |
case Fizz() => println("Fizz") | |
case Buzz() => println("Buzz") | |
case num => println(num.toString()) | |
} | |
} | |
FizzBuzzRunner.run(1) //=> 1 | |
FizzBuzzRunner.run(3) //=> Fizz | |
FizzBuzzRunner.run(4) //=> 4 | |
FizzBuzzRunner.run(5) //=> Buzz | |
FizzBuzzRunner.run(10) //=> Buzz | |
FizzBuzzRunner.run(15) //=> FizzBuzz |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment