1

I am trying to convert each list integer to its absolute value using the following Scala statement, I am getting an invalid type match error:

def f(arr:List[Int]):List[Int] = arr.map((x: Int) => if(x<0) -1*x)





Solution.scala:2: error: type mismatch;
 found   : List[AnyVal]
 required: List[Int]
def f(arr:List[Int]):List[Int] = arr.map((x: Int) => if(x<0) -1*x)
                                        ^
user3243499
  • 2,953
  • 6
  • 33
  • 75
  • Possible duplicate of [Replace elements in List by condition](https://stackoverflow.com/questions/51001759/replace-elements-in-list-by-condition) – Andrey Tyukin Jun 28 '18 at 10:37
  • 1
    Keep in mind that for the case of `Int.MinValue`, there's no `Int` representation for its absolute value – Chirlo Jun 28 '18 at 10:37
  • Alternative duplicate candidate: [Update the values of a list with their absolute values](https://stackoverflow.com/questions/21219993/update-the-values-of-a-list-with-their-absolute-values). – Andrey Tyukin Jun 28 '18 at 10:51

1 Answers1

2

If you insist on doing it with an if-else, then you need both parts of the if-else expression:

def f(arr:List[Int]):List[Int] = arr.map((x: Int) => if(x < 0) -x else x)

It would be easier with abs, though:

arr.map(_.abs)
Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93