Skip to content

Instantly share code, notes, and snippets.

@non
Created May 8, 2017 21:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save non/f575b2bb8986420440aac2f5c66047ce to your computer and use it in GitHub Desktop.
Save non/f575b2bb8986420440aac2f5c66047ce to your computer and use it in GitHub Desktop.
// this code demonstrates unsoundness in scala (tested in 2.11 and 2.12)
//
// it seems like scala is checking that the return type is a Pipe[_]
// but not a Pipe[E]; maybe due to erasure?
sealed abstract class Pipe[E]
case class Single[E](elem: E) extends Pipe[E]
case class Double[A, B](a: Pipe[A], b: Pipe[B]) extends Pipe[(A, B)]
object Pipe {
def prepare[E](p: Pipe[E]): Pipe[E] =
p match {
case Single(_) =>
p
case Double(a, b) =>
// any Double works -- it's type doesn't have to match E.
Double(Single(1), Single(1))
}
prepare[(String, String)](Double(Single("foo"), Single("bar")))
}
@olafurpg
Copy link

olafurpg commented May 8, 2017

FWIW, here's what dotty reports (with glorious syntax highlighted error messages)

-- Warning: notfantastic.scala:10:17 -------------------------------------------
10 |      case Double(a, b) =>
   |           ^^^^^^^^^^^^
   |       There is no best instantiation of pattern type Double[Any^, Any^]
   |       that makes it a subtype of selector type Pipe[E].
   |       Non-variant type variable B cannot be uniquely instantiated.
   |       (This would be an error under strict mode)
-- [E007] Type Mismatch Error: notfantastic.scala:12:14 ------------------------
12 |        Double(Single(1), Single(1))
   |        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |        found:    Double[A, B]
   |        required: Pipe[E]
   |
   |        where:    A is a type variable with constraint >: Int(1)
   |                  B is a type variable with constraint >: Int(1)

one warning found
one error found

@sledorze
Copy link

sledorze commented May 8, 2017

Dotty error reports really looks awesome :)

@non
Copy link
Author

non commented May 9, 2017

Wow, yeah, those Dotty errors look really great @olafurpg!

@friedbrice
Copy link

We ran into a similar problem with record pulled from Datomic (or was it DynamoDB? Not sure). Fields that were supposed to be List[A] were indeed lists, but didn't contains As. I like your example, though: it's minimal in the sense that it gets right to the root of the issue.

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