Your method should return an Int
instead of Unit
. To print elements iteratively, just insert a println
underneath case head :: tail
:
def multiply(list: List[Int]): Int = list match {
case Nil => 1
case n :: rest =>
println(n)
n * multiply(rest)
}
multiply(List(1,2,3,4))
// 1
// 2
// 3
// 4
// res1: Int = 24
1
solved SCALA PAttern matching with recursive in LIST