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

scala – 左右约束类型签名

发布时间:2020-12-16 09:55:23 所属栏目:安全 来源:网络整理
导读:给出以下AST成功和失败: sealed trait Successcase object FooGood extends Successcase object BarGood extends Successsealed trait Failurecase object FooBad extends Failurecase object BarBad extends Failure 方法签名: def go[A : Failure,B : Su
给出以下AST成功和失败:

sealed trait Success
case object FooGood extends Success
case object BarGood extends Success

sealed trait Failure
case object FooBad extends Failure
case object BarBad extends Failure

方法签名:

def go[A <: Failure,B <: Success](x: Int): Either[A,B] = ???

但是,我想将左和右类型限制为特定于Foo或Bar.

但是下面的代码编译(违背我的意愿):

scala> go[FooBad.type,BarGood.type](5)
scala.NotImplementedError: an implementation is missing

如何在编译时实现此约束?

解决方法

这是一个依赖于类型类的解决方案.值得注意的是,它不需要为每个(一对)AST节点手动定义新的类型实例.
它确实涉及为每对引入一个公共超类型(虽然您在技术上不必将其用作基类,但它仅用作标记类型).

sealed trait Success[T]
abstract sealed class Foo
abstract sealed class Bar
case object FooGood extends Foo with Success[Foo]
case object BarGood extends Bar with Success[Bar]
sealed trait Failure[T]
case object FooBad extends Foo with Failure[Foo]
case object BarBad extends Bar with Failure[Bar]

@annotation.implicitNotFound("Expecting reciprocal Failure and Success alternatives,but got ${A} and ${B}")
trait IsGoodAndBadFacet[A,B]
implicit def isGoodAndBadFacet[T,A,B](implicit e1: A <:< Failure[T],e2: B<:<Success[T]): IsGoodAndBadFacet[A,B] = null

def go[A,B](x: Int)(implicit e: IsGoodAndBadFacet[A,B]): Either[A,B] = ???

Repl测试:

scala> go[FooBad.type,BarGood.type](5)
<console>:17: error: Expecting reciprocal Failure and Success alternatives,but got FooBad.type and BarGood.type
              go[FooBad.type,BarGood.type](5)
                                           ^

scala> go[FooBad.type,FooGood.type](5)
scala.NotImplementedError: an implementation is missing
  at scala.Predef$.$qmark$qmark$qmark(Predef.scala:225)
  at .go(<console>:11)
  ... 33 elided

scala> go[BarBad.type,BarGood.type](5)
scala.NotImplementedError: an implementation is missing
  at scala.Predef$.$qmark$qmark$qmark(Predef.scala:225)
  at .go(<console>:11)
  ... 33 elided

(编辑:李大同)

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

    推荐文章
      热点阅读