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

Is there a way to switch to type 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, which 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 possible somehow with the usual Scala type option?

+5
source share
2 answers

there is a solution here that uses a path dependent type to restore the 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 strongly inspired by this slide of a brilliant presentation: http://wheaties.imtqy.com/Presentations/Scala-Dep-Types/dependent-types.html#/2/1

You have a function that gets opaque A, but you are restoring the fact that this is an option and the internal type is implicit through IsOption[A] .

I understand that this is not exactly what you asked for, but when you use such types depending on the type. you need to have a specific value from which you are restoring the type.

+2
source

You can write a simple type function like this:

 scala> type X = Some[Int] defined type alias X scala> type F[H <: Option[A], A] = A defined type alias F scala> type Y = F[X, Int] defined type alias Y scala> implicitly[Y =:= Int] res3: =:=[Y,Int] = <function1> 

Without partial application of the parameter parameter, the output is not very useful, but it works ...

+1
source

Source: https://habr.com/ru/post/1266348/


All Articles