Scala: specify a default generic type instead of Nothing

前端 未结 3 1205
小蘑菇
小蘑菇 2020-12-31 08:04

I have a pair of classes that look something like this. There\'s a Generator that generates a value based on some class-level values, and a GeneratorFact

3条回答
  •  时光说笑
    2020-12-31 08:35

    One option is to move the summoning of the CanBuildFrom to a place where it (or, rather, its instances) can help to determine S,

    case class Generator[T,S](a: T, b: T, c: T)(implicit bf: CanBuildFrom[S, T, S]) {
      def generate : S =
        bf() += (a, b, c) result
    }
    

    Sample REPL session,

    scala> val g2 = Generator('a', 'b', 'c')
    g2: Generator[Char,String] = Generator(a,b,c)
    
    scala> g2.generate
    res0: String = abc
    

    Update

    The GeneratorFactory will also have to be modified so that its build method propagates an appropriate CanBuildFrom instance to the Generator constructor,

    case class GeneratorFactory[T]() {
      def build[S](seq: S)(implicit conv: S => Seq[T], bf: CanBuildFrom[S, T, S]) =
        Generator[T, S](seq(0), seq(1), seq(2))
    }
    

    Not that with Scala < 2.10.0 you can't mix view bounds and implicit parameter lists in the same method definition, so we have to translate the bound S <% Seq[T] to its equivalent implicit parameter S => Seq[T].

提交回复
热议问题