I'm attempting to extend the functionality described in this excellent article by Miles Sabin: Unboxed Union Types to support n-ary type unions, e.g.:
def if[T](t: T)(implicit ev: T <<: (Int | String | Symbol | Double)): String = ???
I've modified Sabin's code and written my own version of the <:<
operator as show below.
object UnboxedTypeUnion extends TypeUnion {
def is[T](t: T)(implicit ev: T <<: (Int | String | Double | Symbol)) =
t match {
case _: Int => "int"
case _: String => "string"
case _: Double => "double"
case _: Symbol => "symbol"
}
// Does not compile
val x = implicitly[Int <<: (Int | String | Double)]
val y = implicitly[Int <<: Not[Not[Not[Not[Int]]]]]
}
trait TypeUnion {
type Not[A] = A => Nothing
type |[A, B] = Not[Not[A] with Not[B]]
sealed abstract class <<:[-A, +B] extends (A => B)
object <<: {
val singleton = new <<:[Any, Any] { override def apply(v1: Any): Any = v1 }
implicit def instance[A]: A <<: A = singleton.asInstanceOf[A <<: A]
implicit def negation[A]: A <<: Not[Not[A]] = singleton.asInstanceOf[A <<: Not[Not[A]]]
implicit def transitivity[A, B, C](implicit ab: A <<: B, bc: B <<: C): A <<: C = singleton.asInstanceOf[A <<: C]
}
}
The underlying issue is that each additional logical disjunction (OR
) wraps the resulting evidentiary subclass in a new double negation, i.e.
implicitly[Not[Not[Int]] <<: (Int | String)]
implicitly[Not[Not[Not[Not[Int]]]] <<: (Int | String | Double )]
implicitly[Not[Not[Not[Not[Not[Not[Int]]]]]] <<: (Int | String | Double | Symbol )]
// etc.
In theory, I would expect the definition of double negation identity in conjunction with a definition of transitivity to allow for this to work, however I am unable to get this to compile. Does anyone know if this is possible, or if recursively chained generics is beyond the capabilities of the Scala compiler?