【问题标题】:scala - Mixin type constraints still compilesscala - Mixin 类型约束仍然可以编译
【发布时间】:2014-05-11 23:49:19
【问题描述】:

接着从 Enforce type difference

我注意到这是编译,但不知道为什么。

trait NotFuture {

  type Out[+T]

  implicitly[Out[_] =!= scala.concurrent.Future[_]]
}

val newNotFuture = new NotFuture {
  type Out[+T] = scala.concurrent.Future[T]
}

知道如何进行这项工作吗?

【问题讨论】:

    标签: scala types


    【解决方案1】:

    不幸的是,在实际定义 Out 之前,我认为不可能构造所需的不等式证明。我能得到的最接近你想要的东西是这样的,

    scala> import shapeless._ // for =:!=
    import shapeless._
    
    scala> import scala.concurrent.Future
    import scala.concurrent.Future
    
    scala> trait NotFuture {
         |   type Out[+T]
         |   val ev: Out[_] =:!= Future[_]
         |   def prf(implicit ev: Out[_] =:!= Future[_]) = ev
         | }
    defined trait NotFuture
    
    scala> val nf = new NotFuture { type Out[+T] = List[T] ; val ev = prf }
    nf: NotFuture{type Out[+T] = List[T]} = $anon$1@5723cc36
    
    scala> val nf = new NotFuture { type Out[+T] = Future[T] ; val ev = prf }
    <console>:12: error: ambiguous implicit values:
     both method neqAmbig1 in package shapeless of type [A]=> shapeless.=:!=[A,A]
     and method neqAmbig2 in package shapeless of type [A]=> shapeless.=:!=[A,A]
     match expected type shapeless.=:!=[this.Out[_],scala.concurrent.Future[_]]
           val nf = new NotFuture { type Out[+T] = Future[T] ; val ev = prf }
    

    请注意,提供证明是强制性的(因为evNotFuture 中是抽象的)并在子类中半隐式提供(val ev = prf)。

    【讨论】:

    • 为此干杯。我看看能不能解决我的问题
    猜你喜欢
    • 1970-01-01
    • 2018-07-27
    • 1970-01-01
    • 2011-01-17
    • 2017-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多