加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 从`Some [A]`到’A`

发布时间:2020-12-16 18:37:08 所属栏目:安全 来源:网络整理
导读:有没有办法,从某些[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) {
有没有办法,从某些[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 Option类型,这也可以吗?

解决方法

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

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]恢复它是一个选项和内部类型的事实.

我很欣赏这不是你要求的,但是当你使用这种类型依赖类型时.您需要具有从中恢复类型的具体值.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读