Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@bvenners
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bvenners/7dbc093d36bd973c993e to your computer and use it in GitHub Desktop.
Save bvenners/7dbc093d36bd973c993e to your computer and use it in GitHub Desktop.
Adding stricter cons and contain operators to covariant lists via an implicit class
scala> implicit class BVList[A](xs: List[A]) {
| def :=:(x: A): List[A] = x :: xs
| def containz(elem: A): Boolean = xs.contains(elem)
| }
defined class BVList
scala> val xs = List(1, 2, 3)
xs: List[Int] = List(1, 2, 3)
scala> 5.0 :: xs
res0: List[AnyVal] = List(5.0, 1, 2, 3)
scala> 5.0 :=: xs
<console>:13: error: type mismatch;
found : Double
required: Int
5.0 :=: xs
^
scala> 5 :=: xs
res2: List[Int] = List(5, 1, 2, 3)
scala> xs contains "bob"
res3: Boolean = false
scala> xs containz "bob"
<console>:13: error: type mismatch;
found : String("bob")
required: Int
xs containz "bob"
^
scala> xs containz 3
res5: Boolean = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment