Juh_
Juh_

Reputation: 15539

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

Upvotes: 1

Views: 148

Answers (2)

Luka Jacobowitz
Luka Jacobowitz

Reputation: 23512

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.

Upvotes: 7

Juh_
Juh_

Reputation: 15539

I found a way, using implicit class:

implicit class MyMap[A](a: A) {
  def myMap[B](f: A => B): B = f(a)
}

// then I can call
List(1,13,42).myMap(_*2)

Upvotes: 0

Related Questions