Search code examples
scalaarraylisttuplesoperators

How to multiply a tuple or a list of integers with a factor in Scala


In Scala 2 I have a tuple like this:

val direction = (2,3) 

This value direction I want to multiply with a Int factor f in order to get a new tuple

(2 * f, 3 * f)

So if f=4 I looking for the result (8,12).

I tried the obvious candidate *:

(2,3) * f

but * doesn't seem to be designed for these types.


Solution

  • Also TupleN has productIterator:

    (1,2,3,4,5)
      .productIterator
      .map { case n: Int => n * 2 }
      .toList
    

    This doesn't return another tuple but gives you easy iteration through all elements without adding any new libraries.

    productIterator returns Iterator[Any] so you gotta use pattern matching.