更新:我修改了示例,以便可以编译和测试。
我有一个定义丰富方法的隐式类:
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
吗?如果将来发生变化,代码将停止工作,因为我将有两个不同的适用隐式。