Scala 如何使以下代码类型安全?
比如说,我有一个通用的命令特性,它带有一个接收输入并返回输出的execute方法。差不多Scala 如何使以下代码类型安全?,scala,types,Scala,Types,比如说,我有一个通用的命令特性,它带有一个接收输入并返回输出的execute方法。差不多 trait Input; trait Output; trait Command[I <: Input, O <: Output] { def execute(input: I): O; } class SampleInput extends Input class SampleOutput extends Output class SampleCommand extends Comm
trait Input;
trait Output;
trait Command[I <: Input, O <: Output] {
def execute(input: I): O;
}
class SampleInput extends Input
class SampleOutput extends Output
class SampleCommand extends Command[SampleInput, SampleOutput] {
def execute(input:SampleInput):SampleOutput = new SampleOutput()
}
问题是我可以创建一个带有SampleAInput
和SampleBOutput
的命令,编译器会欣然接受。如何强制执行该操作,使编译器因类型不匹配错误而失败
不知何故,我需要将输入
和输出
分组到一个类型下,并传递该类型以创建一个
指挥部。如何做到这一点?由于您的限制条件是输入和输出的类型相同,因此我将尝试以下方法: trait Input[T] trait Output[T] trait Command[T] { def execute[I <: Input[T], O <: Output[T]](i: I): O } 特征输入[T] 性状输出[T] 特征命令[T]{ def execute[I
trait InputOutput{
类型输入
类型输出
}
trait Command[IO我有点晚了,但是这个怎么样:
object inout {
trait ~>[I, O]
trait FooInput
trait FooOutput
trait BarOutput
//this specifies a valid input-output combination
implicit object fooInOut extends ~>[FooInput,FooOutput]
class Command[I, O](implicit val valid: I ~> O) {
def execute(input: I): O;
}
class FooCommand extends Command[FooInput, FooOutput]
//won't compile:
//class FubarCommand extends Command[FooInput, BarOutput]
}
太好了!这正是我想要的。谢谢。我喜欢它,不需要在同一个特性中耦合输入和输出。
trait InputOutput {
type Input
type Output
}
trait Command[IO <: InputOutput] {
def execute(input: IO#Input): IO#Output
}
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}
^
object inout {
trait ~>[I, O]
trait FooInput
trait FooOutput
trait BarOutput
//this specifies a valid input-output combination
implicit object fooInOut extends ~>[FooInput,FooOutput]
class Command[I, O](implicit val valid: I ~> O) {
def execute(input: I): O;
}
class FooCommand extends Command[FooInput, FooOutput]
//won't compile:
//class FubarCommand extends Command[FooInput, BarOutput]
}