Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping a Scala function with an optional parameter

I'm having trouble mapping a function that takes an optional parameter. I get the same type error as I would if the parameter were not optional. Here's a simple illustration:

scala> def multiple(m: Int, n: Int = 2) = m * n
multiple: (m: Int,n: Int)Int

scala> multiple(5)
res0: Int = 10

scala> multiple(5, 7)
res1: Int = 35

scala> (1 to 10).map(multiple)
<console>:7: error: type mismatch;
 found   : (Int, Int) => Int
 required: (Int) => ?
       (1 to 10).map(multiple)

Here's one way to make it work, but it requires repeating the default argument, which is a maintenance nightmare:

scala> (1 to 5).map { n => multiple(n, 2) } 
res6: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 6, 8, 10)

Is there a better way to do it? More generally, why does a function with an optional parameter seem to have the same type as it would if the parameter was not optional? What is the actual type of multiple?

like image 789
dkh Avatar asked Apr 05 '11 05:04

dkh


1 Answers

This seems to work:

(1 to 10).map(multiple(_)) 

//res0: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)
like image 60
Landei Avatar answered Oct 02 '22 13:10

Landei