2017-04-05 26 views
5

有没有什么办法,从Some[A]A的类型?从`某些[A]`到`A`

type X = Some[Int] 
type Y = ??? // what do I have to write here to get `Int` 

我可以定义自己的Option型,允许这样的:

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 

与正常斯卡拉选项类型某种程度上这是也有可能?

+0

这让我想起HTTPS的:// stackoverflow.com/questions/29038214/why-scala-does-not-have-a-decltype and https://stackoverflow.com/questions/29034921/can-function-type-be-defined-by-inference – Suma

+1

我认为一般情况下,这可能是不可能的,但取决于你的用例,你可以通过'def x [T](opt:Option [T]){/ * T在这里可用* /}'或者路径依赖ty PE。 –

回答

2

这里是一个使用路径依赖型从价值恢复类型的解决方案:

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]隐含内部类型。

我明白,这不是你要求的,但当你使用这种类型依赖类型。你需要有一个具体的值从中恢复一个类型。

+0

该解决方案不需要'A'值来获得类型'T',只需要一个隐式的'IsOption [A]'(它将始终在需要的范围内)。所以这就是IMO要求的。 –

+0

但是,你不能做类似'type Inner = IsOption [Option [Int]]#T' 但是,像'def getInner [A](隐式inner:IsOption [A]):Option [ .T] = ???'是有效的,但可能是有限的值。 –

+2

你可以'val isOpt =隐式[Option [T]];键入Inner = isOpt.T' –

1

如下您可以编写一个简单的类型功能:

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> 

没有部分类型参数的应用程序/推断它不是非常有用的,但它的工作原理...

相关问题