gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:33:31 25 4
gpt4 key购买 nike

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

我有一个定义丰富方法的隐式类:

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;
}

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

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
^

...我承认这与您发布的错误不同。但我并不完全相信你发布的内容,所以我要继续!解决这个问题的方法是制作 Test其类型参数的协变 A :

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

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

编辑

我只花了几分钟浏览 Scala bug list并发现了几个可能相关的问题:SI-1570 , SI-4509 , SI-4982SI-5505 .我真的不知道任何细节,但听起来像 Nothing被特殊对待,不应该。 Paul 和 Adriaan 会问...

关于scala - 当其中一个类型参数应该为 Nothing 时,为什么 Scala 的隐式类不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15310451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com