比方说,我有一个带有执行方法的通用命令trait,它接受一个Input并返回一个Output.就像是
trait Input;
trait Output;
trait Command[I <: Input, O <: Output] {
def execute(input: I): O;
}
Run Code Online (Sandbox Code Playgroud)
然后,我将创建各种命令,类似于
class SampleInput extends Input
class SampleOutput extends Output
class SampleCommand extends Command[SampleInput, SampleOutput] {
def execute(input:SampleInput):SampleOutput = new SampleOutput()
}
Run Code Online (Sandbox Code Playgroud)
这里的问题是,我可以创建命令与SampleAInput和SampleBOutput编译器会接受愉快.我如何强制执行,以便编译器因类型不匹配错误而失败?
不知何故,我需要在类型下进行分组Input并Output传递该类型以创建命令.我怎么做?
Itt*_*ayD 18
trait InputOutput {
type Input
type Output
}
trait Command[IO <: InputOutput] {
def execute(input: IO#Input): IO#Output
}
Run Code Online (Sandbox Code Playgroud)
这是一些用法:
scala> trait SampleIO extends InputOutput {type Input = String; type Output = String}
defined trait SampleIO
scala> class SampleCommand extends Command[SampleIO] {def execute(input: String) = input}
defined class SampleCommand
scala> class SampleCommand extends Command[SampleIO] {def execute(input: String) = 1}
<console>:13: error: type mismatch;
found : Int(1)
required: SampleIO#Output
class SampleCommand extends Command[SampleIO] {def execute(input: String) = 1}
^
Run Code Online (Sandbox Code Playgroud)
由于您的约束是输入和输出的类型相同,我会尝试以下方法:
trait Input[T]
trait Output[T]
trait Command[T] {
def execute[I <: Input[T], O <: Output[T]](i: I): O
}
让我们尝试两种不同的类型.
class SampleInput extends Input[String]
class SampleOutput extends Output[Int]
scala> class SampleCommand extends Command[String] {
| def execute(input: SampleInput): SampleOutput = new SampleOutput
| }
:10: error: class SampleCommand needs to be abstract, since method execute in trait Command of type [I <: Input[String],O <: Output[String]](i: I)O is not defined
class SampleCommand extends Command[String] {
^
| 归档时间: |
|
| 查看次数: |
637 次 |
| 最近记录: |