繁体   English   中英

当其中一个类型参数应该是Nothing时,为什么Scala的隐式类不起作用?

[英]Why doesn't Scala's implicit class work when one of the type parameters should be Nothing?

更新:我修改了示例,以便可以编译和测试。

我有一个定义浓缩方法的隐式类:

case class Pipe[-I,+O,+R](f: I => (O, R));

object Pipe {
  // The problematic implicit class:
  implicit class PipeEnrich[I,O,R](val pipe: Pipe[I,O,R]) extends AnyVal {
    def >->[X](that: Pipe[O,X,R]): Pipe[I,X,R] = Pipe.fuse(pipe, that);
    def <-<[X](that: Pipe[X,I,R]): Pipe[X,O,R] = Pipe.fuse(that, pipe);
  }

  def fuse[I,O,X,R](i: Pipe[I,O,R], o: Pipe[O,X,R]): Pipe[I,X,R] = null;

  // Example that works:
  val p1: Pipe[Int,Int,String] = Pipe((x: Int) => (x, ""));
  val q1: Pipe[Int,Int,String] = p1 >-> p1;

  // Example that does not, just because R = Nothing:
  val p2: Pipe[Int,Int,Nothing] = Pipe((x: Int) => (x, throw new Exception));
  val q2: Pipe[Int,Int,String] = p2 >-> p2;
}

问题是当第二个例子中RNothing时它不起作用。 它导致编译器错误:在这种情况下,我得到以下编译器错误:

 Pipe.scala:19: error: type mismatch; found : Pipe[Int,Int,R] required: Pipe[Int,Int,String] val q2: Pipe[Int,Int,String] = p2 >-> p2; 

为什么会这样?


我设法通过为该案例创建一个单独的隐式类来解决它:

trait Fuse[I,O,R] extends Any {
  def >->[X](that: Pipe[O,X,R])(implicit finalizer: Finalizer): Pipe[I,X,R];
}

protected trait FuseImpl[I,O,R] extends Any with Fuse[I,O,R] {
  def pipe: Pipe[I,O,R];
  def >->[X](that: Pipe[O,X,R]) = Pipe.fuse(pipe, that);
  def <-<[X](that: Pipe[X,I,R]) = Pipe.fuse(that, pipe);
}

implicit class PipeEnrich[I,O,R](val pipe: Pipe[I,O,R])
  extends AnyVal with FuseImpl[I,O,R];
implicit class PipeEnrichNothing[I,O](val pipe: Pipe[I,O,Nothing])
  extends AnyVal with FuseImpl[I,O,Nothing];

但是,我可以在将来依赖Scala的行为,它不会将Nothing视为R的选项吗? 如果将来发生变化,代码将停止工作,因为我将有两个不同的适用含义。

嗯...你没有显示所有代码,你所展示的代码有一些令人困惑的不一致。 所以这将是一个疯狂的猜测。 我怀疑你的问题是Pipe在其类型参数R是不变的。 这是我的简化示例:

case class Test[A](a: A)

object Test {
  implicit class TestOps[A](val lhs: Test[A]) extends AnyVal {
    def >->(rhs: Test[A]): Test[A] = ???
  }

  def test {
    def lhs = Test(???)
    def rhs = Test(???)
    lhs >-> rhs
  }
}

我从这段代码得到的编译错误是:

value >-> is not a member of Test[Nothing]
     lhs >-> rhs
         ^

...我承认与你发布的错误不一样。 但我并不完全相信你发布的内容,所以我会继续前进! 对此的修复是在其类型参数A中使Test协变:

case class Test[+A](a: A)

老实说,我不明白为什么编译错误会发生。 似乎编译器不想在转换为TestOps统一A =:= Nothing ,但我不明白为什么不。 尽管如此, TestA应该是协变的,我猜你的Pipe类同样应该在R是协变的。

编辑

我只花了几分钟查看Scala错误列表 ,发现了几个可能相关的问题: SI-1570SI-4509SI-4982SI-5505 我真的不知道任何细节,但听起来Nothing特别对待,不应该。 保罗和亚德里安会问这些人......

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM