Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get from `Some[A]` to `A`

Tags:

scala

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?

like image 754
Fabian Schmitthenner Avatar asked Oct 17 '22 14:10

Fabian Schmitthenner


1 Answers

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.

like image 70
V-Lamp Avatar answered Nov 15 '22 05:11

V-Lamp