Skip to content

Instantly share code, notes, and snippets.

@pathikrit
Last active August 3, 2016 16:17
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pathikrit/0c2538fa8faec51fc2f23b9c5e4194c9 to your computer and use it in GitHub Desktop.
Save pathikrit/0c2538fa8faec51fc2f23b9c5e4194c9 to your computer and use it in GitHub Desktop.
Simple Negation Types in Scala
trait NotSubTypeOf[A, B] // encoding to capture A is not a subtype of B
// Note: We can use infix notation to write `A NotSubTypeOf B` instead of `NotSubTypeOf[A, B]`
// evidence for any two arbitrary types A and B, A is not a subtype of B
implicit def isSub[A, B]: A NotSubTypeOf B = null
// define ambigous implicits to trigger compile error in case A is a subtype of B (or A =:= B)
implicit def iSubAmbig1[A, B >: A]: A NotSubTypeOf B = null
implicit def iSubAmbig2[A, B >: A]: A NotSubTypeOf B = null
// A type lambda: https://github.com/earldouglas/scala-scratchpad/tree/master/type-lambdas
type Not[T] = {
type L[U] = U NotSubTypeOf T
}
// foo() accepts any A that is not a string.
// Note with kind-projector (https://github.com/non/kind-projector), this can be much more readable
def foo[A: Not[String]#L](a: A) = {
println(a)
}
foo(23) // compiles
foo(true) // compiles
//foo("hello") // does not compile; better error message would be possible in Scala 2.12: https://github.com/scala/scala/pull/4673
@ryantheleach
Copy link

This could be useful as a security feature I guess. Never send anything of trait sensitive to user facing output?

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