Last active
December 24, 2015 15:59
-
-
Save zakki/6824126 to your computer and use it in GitHub Desktop.
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
| sealed trait NameOpt extends Any { | |
| def isEmpty: Boolean | |
| def get: (String, String) | |
| } | |
| object NameOpt { | |
| object Empty extends NameOpt { | |
| def isEmpty: Boolean = | |
| true | |
| def get: (String, String) = | |
| throw new UnsupportedOperationException("Method get not defined for NameOpt.Empty!") | |
| } | |
| class FirstLast(val parts: (String, String)) extends AnyVal with NameOpt { | |
| def isEmpty: Boolean = | |
| false | |
| def get: (String, String) = | |
| parts | |
| } | |
| } | |
| object Name { | |
| def unapply(name: String): NameOpt = { | |
| val parts = name split " " | |
| if (parts.length == 2) | |
| new NameOpt.FirstLast((parts(0), parts(1))) | |
| else | |
| NameOpt.Empty | |
| } | |
| } | |
| class NameOpt2(val parts: Array[String]) extends AnyVal with NameOpt { | |
| def isEmpty: Boolean = | |
| parts.length != 2 | |
| def get: (String, String) = | |
| (parts(0), parts(1)) | |
| } | |
| object Name2 { | |
| def unapply(name: String): NameOpt2 = { | |
| val parts = name split " " | |
| new NameOpt2(parts) | |
| } | |
| } | |
| object App { | |
| def a() = { | |
| List("First", "First Last") map (_ match { | |
| case Name(f, l) => | |
| println(f + "/" + l) | |
| case v => | |
| println(v) | |
| }) | |
| } | |
| def b() = { | |
| List("First", "First Last") map (_ match { | |
| case Name2(f, l) => | |
| println(f + "/" + l) | |
| case v => | |
| println(v) | |
| }) | |
| } | |
| def main(args: Array[String]) { | |
| a() | |
| b() | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment