The best way is to use Scala functions like @senia suggested in comments. For example:
val res = list map math.abs
But if you want to fix your code just replace to
with until
. You are getting off by one error:
def f (arr:List[Int]) : List[Int] =
{
val list = new scala.collection.mutable.ListBuffer[Int]();
val len = arr.length;
for ( i <- 0 until len)
{
if(arr(i) < 0)
{
list.append((-1)*arr(i)) ;
}
else
{
list.append(arr(i));
}
}
return list.toList;
}
Here is the difference between until
and to
:
1 to 3
// Range(1, 2, 3)
1 until 3
// Range(1, 2)
You can also remove return
, ;
and even braces {
used with if/else
.