how can make work? task @ hand little bit more complicated boils down this:
object z { class b extends function1[int, int] { def apply(i: int): int = } def compose[t <: function1[x, x], x](fcts: list[t]): function1[x, x] = { fcts.reduce(_ andthen _) } def test() = { val fcts = list.empty[b] // unspecified type parameter x val composed: function1[int, int] = compose[b](fcts) } }
i don't know how define "compose" function able receive concrete class b , automatically infer dependent types x
the scala compiler not when trying infer multiple levels of type parameters have. instead, simpler remove t <: function1[x, x]
, require single type parameter represents argument , return type of function1
.
def compose[a](fcts: list[function1[a, a]]): function1[a, a] = { fcts.reduce(_ andthen _) }
the compiler have easier time inferring a
, instead of trying figure out t
, x
are, when x
part of type t
.
val a: int => int = _ + 10 val b: int => int = _ * 2 val c: int => int = _ - 3 scala> val f = compose(list(a, b, c)) f: int => int = scala.function1$$lambda$1187/930987088@531ec2ca scala> f(2) res1: int = 21
note reduce
throw exception empty list of functions.
Comments
Post a Comment