2010-12-20 9 views
6

कहता है, मेरे पास एक निष्पादन विधि के साथ एक सामान्य कमांड विशेषता है जो एक इनपुट लेता है और आउटपुट देता है।निम्नलिखित कोड प्रकार को सुरक्षित कैसे करें?

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 और संकलक कि खुशी से स्वीकार करेंगे के साथ एक कमांड बना सकते है जा रहा हूँ । मैं इसे कैसे लागू करूं ताकि संकलक टाइप मिस्चैच त्रुटि के साथ विफल हो जाए?

किसी तरह, मैं एक प्रकार के अंतर्गत समूह Input और Output करने की जरूरत है और उस प्रकार एक आदेश बनाने के लिए गुजरती हैं। मैं उसको कैसे करू?

उत्तर

18
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} 
                       ^
+0

उत्कृष्ट! यह वहीं है जिसे मैं ढूंढ रहा था। धन्यवाद IttayD। – sanjib

6

के बाद से अपने बाधा है कि इनपुट और आउटपुट के प्रकार के एक ही होना है, मैं निम्नलिखित की कोशिश करेंगे:

 
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] { 
      ^
+0

मुझे यह पसंद है, कुछ इनपुट करने की कोई जरूरत और एक ही विशेषता में उत्पादन। – GClaramunt

0

मैं थोड़ा देर हो रही है, लेकिन कैसे इस बारे में:

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] 
} 
संबंधित मुद्दे