Last active
December 18, 2015 16:39
-
-
Save cb372/5812875 to your computer and use it in GitHub Desktop.
Python-style "x in xs" testing in Scala using implicit conversion and duck typing.
Sinful but convenient.
This file contains 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
scala> implicit class WithInMethod(obj: Any) { | |
| def in(a: {def contains(e: Any): Boolean}): Boolean = a.contains(obj) | |
| } | |
warning: there were 1 feature warnings; re-run with -feature for details | |
defined class WithInMethod | |
scala> "foo" in List("1", "2") | |
res3: Boolean = false | |
scala> "foo" in List("foo", "bar") | |
res4: Boolean = true | |
scala> "foo" in Map("1" -> 1, "2" -> 2) | |
res5: Boolean = false | |
scala> "foo" in Map("foo" -> 1, "bar" -> 2) | |
res6: Boolean = true |
This file contains 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
scala> implicit class WithInAndNotMethods(obj: Any) { | |
| def in(a: {def contains(e: Any): Boolean}): Boolean = a.contains(obj) | |
| def not(f: Any => Boolean): Boolean = !f(obj) | |
| } | |
warning: there were 1 feature warnings; re-run with -feature for details | |
defined class WithInAndNotMethods | |
scala> def in(a: {def contains(e: Any): Boolean}): Any => Boolean = a.contains _ | |
warning: there were 2 feature warnings; re-run with -feature for details | |
in: (a: AnyRef{def contains(e: Any): Boolean})Any => Boolean | |
scala> "foo" in List("foo", "bar") | |
res0: Boolean = true | |
scala> "foo" in List("a", "b") | |
res1: Boolean = false | |
scala> "foo" not in List("foo", "bar") | |
<console>:10: error: type mismatch; | |
found : Any => Boolean | |
required: Boolean | |
"foo" not in List("foo", "bar") | |
^ | |
scala> "foo" not in (List("foo", "bar")) // shame, we have to add parentheses here | |
res3: Boolean = false | |
scala> "foo" not in (List("a", "b")) | |
res4: Boolean = true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment