How to assign abstract type in variable declaration?

53 Views Asked by At

Type Parameter:

    trait Transformer[Input, Output] {
      def transform(input: Input): Output
    }

    trait TransformerCollection[TransformerCollectionInput, TransformerCollectionOutput] {
      def transformers: List[Transformer[TransformerCollectionInput, TransformerCollectionOutput]]
    }

    object Int2StringTransformer extends Transformer[Int, String] {
      def transform(input: Int): String = s"${input}"
    }

    object TwiceInt2StringTransformer extends Transformer[Int, String] {
      def transform(input: Int): String = s"${2*input}"
    }

    object String2StringTransformer extends Transformer[String, String] {
      def transform(input: String): String = s"${input}"
    }

    object TwiceString2StringTransformer extends Transformer[String, String] {
      def transform(input: String): String = s"${input}${input}"
    }

    object Int2StringTransformerCollection extends TransformerCollection[Int, String] {
      def transformers = List(Int2StringTransformer, TwiceInt2StringTransformer)
    }

This code throws a compilation error when I add String2StringTransformer to transformers List.

I can't get an equivalent code with abstract types to work

    trait Transformer {
      type Input
      type Output
      def transform(input: Input): Output
    }

    trait TransformerCollection {
      type TransformerCollectionInput
      type TransformerCollectionOutput
      def transformers: List[Transformer {type Input = TransformerCollectionInput; type Output = TransformerCollectionOutput}]
    }

    object Int2StringTransformer extends Transformer {
      type Input = Int
      type Output = String
      
      def transform(input: Int): String = s"${input}"
    }

    object TwiceInt2StringTransformer extends Transformer {
      type Input = Int
      type Output = String
      def transform(input: Int): String = s"${2*input}"
    }

    object String2StringTransformer extends Transformer {
      type Input = String
      type Output = String
      def transform(input: String): String = s"${input}"
    }

    object TwiceString2StringTransformer extends Transformer {
      type Input = String
      type Output = String
      def transform(input: String): String = s"${input}${input}"
    }

    object Int2StringTransformerCollection extends TransformerCollection {
      type TransformerCollectionInput = Int
      type TransformerCollectionOutput = String
      def transformers = List(Int2StringTransformer, TwiceInt2StringTransformer)
    }

Compilation Error:

Type mismatch. Required: List[Transformer {type Input = TransformerCollectionInput, type Output = TransformerCollectionOutput}], found: List[Transformer]

How do I achieve the same behaviour with Abstract Types?

0

There are 0 best solutions below