【发布时间】:2016-11-01 09:06:08
【问题描述】:
由于最后一行,以下内容无法编译:
object ImplicitWrappedTraitWithType {
trait Wrapper[+T] {
def unwrap: T
}
object Wrapper {
def apply[T](implicit w: Wrapper[T]): Wrapper[T] = w
}
trait IO[In] {
type Out
def out: Out
}
implicit def decoder[In]: Wrapper[IO[In] {type Out = String}] = new Wrapper[IO[In] {type Out = String}] {
override def unwrap: IO[In] {type Out = String} = new IO[In] {
override type Out = String
override val out: Out = "yeah"
}
}
val wrap = Wrapper[IO[String]]
val io: IO[String] = wrap.unwrap
val out: String = io.out //actual type: unwrap.Out
}
我该怎么做才能让编译器相信val out 是String?
预编辑 - 忽略此
示例 1 - 无法编译:
object ImplicitWrappedTraitWithType {
class Wrapper[T]
object Wrapper {
def apply[T](implicit w: Wrapper[T]): Wrapper[T] = w
}
trait IO[In] {
type Out
}
implicit def decoder[In]: Wrapper[IO[In] {type Out = String}] = null
//client code
Wrapper[IO[String]]
}
示例 2 - 而这样做:
object ImplicitWrappedTraitWithType {
class Wrapper[T]
object Wrapper {
def apply[T](implicit w: Wrapper[T]): Wrapper[T] = w
}
trait IO[In] {
type Out
}
implicit def decoder[In]: Wrapper[IO[In]] = null
//client code
Wrapper[IO[String]]
}
在客户端代码中,我不知道Out 的类型是什么,但是当我从Wrapper 提取IO 的实例时我需要能够访问它(未显示的代码)。
必须如何更改“示例 1”才能编译,同时以客户端代码可见的方式保留 Out 参数。
(如果这个表述不清楚,请评论)
【问题讨论】:
-
在客户端代码中我不知道 Out 的类型是什么,但是当我从 Wrapper 提取 IO 实例时我需要能够访问它但您可以通过
IO[T].Out看到它。我不确定我是否理解这个问题。 -
@YuvalItzchakov 在第二个示例中
Out不受约束。 -
@Jasper-M 我看到它是不受约束的,但我不确定 OP 是否希望它成为他所说的“可见性”。我试图理解他的意思。
-
更新问题
-
辅助模式在这里可能会有所帮助:gigiigig.github.io/posts/2015/09/13/aux-pattern.html
标签: scala generics type-parameter type-alias type-members