Search code examples
scalatype-inferencegeneric-type-argument

Automatic type-argument inference in scala


I tried to implement a function similar to:

def myMap[A,B](a: Seq[A], f: A => B): Seq[B] = a.map(f)

// then I want to call it like that:
myMap(List(1,13,42), _*2)

But the call to myMap doesn't compile because the compiler cannot infer the type arguments A and B. error: missing parameter type

Basically, I hoped that it would infer A (Int) given argument List(1,13,42) then infer B from given f = _*2 knowing A. But it doesn't.

What could I do to avoid writing the type arguments?

The best I found was:

def myMap[A,B](a: Seq[A], f: A => B): Seq[B] = a.map(f)
myMap(List(1,13,42), (a: Int) => a*2)

I.e. I explicitly give A in the f argument


Solution

  • Use multiple parameter lists.

    def myMap[A,B](a: Seq[A])(f: A => B): Seq[B] = a.map(f)
    
    // then call it like this:
    myMap(List(1,13,42)) (_*2)
    

    The collection api makes heavy use of this style for foldLeft and similar functions. You can check the official style guide here.