I have the following problem: I have a function that takes a List [Double] parameter as a parameter, performs some arithmetic operations on list items, and returns the result. I would like the function to also accept List [Int]. Here is an example:
def f(l: List[Double]) = { var s = 0.0 for (i <- l) s += i s } val l1 = List(1.0, 2.0, 3.0) val l2 = List(1, 2, 3) println(f(l1)) println(f(l2))
Of course, the second println fails, since f requires List [Double], not List [Int].
Also, pay attention to the statement of the style of not scala sums inside the function f, to prove the necessity of using 0 (or other constants) inside the function itself (if I sum the values โโof Int, I must initialize s to 0 not 0.0.
What is the best way (less code) to get a function to work with both Double and Int?
(I saw something around a 2.8 numerical sign, I'm not sure how to use it ...)
Thank you all for your help.
Filippo tabusso
source share