我有一组继承自Step[I, O]的类,其中I是输入,O是输出。我想定义一个更具体的子类,它不关心I。
以下是我的定义:
trait Step[I, O] {
def apply(c:Context, i:I):Either[Error, O]
}
// H : Action handler
// A : Action handled by H
// R : Result of successful A
class Legacy[H, A <: Action[H], R](action: A with Result[R], handler: H) extends Step[Any, R] {
override def apply(c:Context, a: Any): Either[Error, R] = {
handler.run(action)
}
}但是,这些步骤是通过使用步骤的输出O作为下一个步骤的输入I的DSL链接的。
// DSL excerpt
class AndThenBuilder[I] {
def andThen[O](producer: (Context, I) => Step[I, O]) = ???
}
//...
val intToString:Step[Int, String] = //new SubType of Step
val legacy:Step[Any, String] = // new Legacy( action with Result[String])
//...
execute(intToString) // return AndThenBuilder[String]
.andThen((_:Context, s:String)=>legacy)最后一行不编译,因为DSL验证类型:
必需:(上下文,字符串) => StepString,NotInferedO
找到:(上下文,字符串) => StepAny,String
我想将Step[I, O]改为Step[I_Or_Subtypes, O]可以解决我的问题。但是我找不到在Step或Legacy中定义它的语法,每次尝试都会给我一个更神秘的消息。
有人能帮我修改我的代码吗?这样Step[Any, String]就可以被接受为Step[String, String]了。(我可以将Any改为其他类型)?
谢谢
发布于 2019-12-19 11:31:39
,以便
Step[Any, String]被接受为Step[String, String]
这需要第一个参数是反向变量,而不是标题中的协变量。语法是
trait Step[-I, O] { ... }碰巧的是,I可以是反向变量,但不是协变量,因为它被用作方法参数类型。而O可以是协变的,但不能是逆变的。
https://stackoverflow.com/questions/59407700
复制相似问题