Skip to content

Instantly share code, notes, and snippets.

@travisbrown
Created March 2, 2014 17:08
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 travisbrown/9309747 to your computer and use it in GitHub Desktop.
Save travisbrown/9309747 to your computer and use it in GitHub Desktop.
Breaking parametricity sucks!
package org.brianmckenna.wartremover
package warts
object Typecase extends WartTraverser {
def apply(u: WartUniverse): u.Traverser = {
import u.universe._
val typedFinder = new Traverser {
override def traverse(tree: Tree) {
tree match {
case Typed(_, _) => u.error(tree.pos, "Type matching is disabled!")
case _ => super.traverse(tree)
}
}
}
new Traverser {
override def traverse(tree: Tree) {
tree match {
case CaseDef(pattern, _, _) => typedFinder.traverse(pattern)
case _ => super.traverse(tree)
}
}
}
}
}
@travisbrown
Copy link
Author

Example of usage:

scala> typecase {
     |   def foo[A](a: A) = a match {
     |     case i: Int => i
     |     case s: String => s.length
     |     case _ => 42
     |   }
     | }
<console>:13: error: Type matching is disabled!
                  case i: Int => i
                        ^
<console>:14: error: Type matching is disabled!
                  case s: String => s.length
                        ^

See e.g. this article for some arguments on the other side.

@jdegoes
Copy link

jdegoes commented Mar 2, 2014

This is not always a wart -- e.g. when pattern matching on case classes with type parameters, Scala sometimes cannot correctly infer the types and you are instead forced to match by type.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment