abcd
abcd

Reputation: 63

How to print list returned by a function

I wrote code which filters some values. I try to print results but I receive :Unit type and nothing is printed. How can I fix the code?

val originalList = List(5, -1, 0, 3, 2)

 def without(originalList: List [Int] ) : List[Int] = {
     val newList = originalList.filter(_ == 3)

      return newList
   }

val list=without(originalList)
for( a <- list ){
         println();
      }

Upvotes: 0

Views: 85

Answers (1)

Raman Mishra
Raman Mishra

Reputation: 2686

Your code is actually fine but you are missing what you need to print inside the for loop you are not giving the value in println which is a.

When you write for(a <- list) that means for a in list where a is the element of the list. And you need to print the element of the list which is a. So you do

println(a)

You can use foreach

without(originalList).foreach(println)

You can directly do println(list)

In your code

val list=without(originalList)
for( a <- list ){
         println(a)
      }

Actually in your code you don’t need return statement as the last line of a function in scala is considered as return value.

val originalList = List(5, -1, 0, 3, 2)

 def without(originalList: List [Int] ) : List[Int] = originalList.filter(_ == 3)

val list=without(originalList)
for( a <- list ){
         println(a)
      }

Upvotes: 4

Related Questions