Last active
August 3, 2016 16:17
-
-
Save pathikrit/0c2538fa8faec51fc2f23b9c5e4194c9 to your computer and use it in GitHub Desktop.
Simple Negation Types in Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This could be useful as a security feature I guess. Never send anything of trait sensitive to user facing output?