有没有办法从Some[A]中获取A的类型
type X = Some[Int]
type Y = ??? // what do I have to write here to get `Int`我可以定义我自己的Option-type来实现这一点:
sealed trait Option[+A]
case object None extends Option[Nothing]
case class Some[+A](a: A) {
type Inner = A
}然后使用
type X = Some[Int]
type Y = X#Inner对于普通的Scala选项类型,这也是可能的吗?
发布于 2017-04-05 17:42:29
下面是一个使用路径依赖类型从值中恢复类型的解决方案:
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)答案从这张精彩演示的幻灯片中得到了很大的启发:http://wheaties.github.io/Presentations/Scala-Dep-Types/dependent-types.html#/2/1
您有一个接收不透明A的函数,但是您通过隐含的IsOption[A]恢复了它是一个选项和内部类型的事实。
我很欣赏这并不完全是您所要求的,但是当您使用这种类型依赖类型时。您需要一个具体的值,以便从中恢复类型。
发布于 2017-04-05 18:01:31
您可以编写一个简单的类型函数,如下所示:
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>如果没有分部类型参数应用/推断,它不是很有用,但它可以工作...
https://stackoverflow.com/questions/43226016
复制相似问题