Is there any way, to get to the type of A
from Some[A]
?
type X = Some[Int]
type Y = ??? // what do I have to write here to get `Int`
I can define my own Option
-type that allows this:
sealed trait Option[+A]
case object None extends Option[Nothing]
case class Some[+A](a: A) {
type Inner = A
}
and then use
type X = Some[Int]
type Y = X#Inner
Is this also possible somehow with the normal Scala Option type?
here is a solution that uses path dependent type to recover type from value:
trait IsOption[F]{
type T
def apply(f: F): Option[T]
}
object IsOption{
def apply[F](implicit isf: IsOption[F]) = isf
implicit def mk[A] = new IsOption[Option[A]]{
type T = A
def apply(f: Option[A]): Option[A] = f
}
}
def getInner[A](in:A)(implicit inner: IsOption[A]): Option[inner.T] = inner(in)
The answer is heavily inspired from this slide of a brilliant presentation: http://wheaties.github.io/Presentations/Scala-Dep-Types/dependent-types.html#/2/1
You have a function that receives an opaque A, but you recover the fact that it is an option and the inner type via the IsOption[A]
implicit.
I appreciate that this is not exactly what you asked for, but when you use such type-dependent types. you need to have a concrete value from which you recover a type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With