Skip to content

Instantly share code, notes, and snippets.

@thsutton
Created July 27, 2017 23:10
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 thsutton/9c322cee3c46f6de1788120016282a67 to your computer and use it in GitHub Desktop.
Save thsutton/9c322cee3c46f6de1788120016282a67 to your computer and use it in GitHub Desktop.
Bound a type parameter to be strictly a subtype.
object Test extends App {
// From https://stackoverflow.com/a/6944070
trait =!=[A, B]
implicit def neq[A, B] : A =!= B = null
// This pair excludes the A =:= B case
implicit def neqAmbig1[A] : A =!= A = null
implicit def neqAmbig2[A] : A =!= A = null
type ¬[T] = T => Nothing
implicit def neg[T, U](t : T)(implicit ev : T =!= U) : ¬[U] = null
// An example:
class Foo(val string: String)
class Bar(val extra: String) extends Foo("bar")
/** Require an argument which is strictly a subtype of [[Foo]]. */
def wut[A <: Foo](t : A)(implicit ev: A =!= Foo): Foo = t
val bar = new Bar("Hello")
val foo = new Foo("nope")
println(bar)
println(foo)
println(wut(bar))
//Error: Could not find implicit value for parameter ev: Test.Foo =!= Test.Foo
//println(wut(foo))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment