user1656125 user1656125 - 6 months ago 25
Scala Question

Recursive method not working. Need ; ?

Trying to create a recursive function that prints the highest element of an array.

It's saying it needs a

else maxi=xs.head
and a

I didn't think scala uses semi colons, when should you use them and what are some other basic syntactical rules.

var maxi = 0
def max(xs: List[Int]): Int = {if (xs.isEmpty) throw new java.util.NoSuchElementException()
else if (xs.tail.isEmpty) maxi
else if (xs.tail.head > xs.head) maxi = xs.tail.head
else maxi=xs.head


Scala uses semicolons, but they're optional at the end of a line. That is if a semicolon would be legal at the end of a line (i.e. the line doesn't end in the middle of an expression (like a +)), one is automatically inserted.

That said, despite the error message your problem doesn't actually have anything to do with semicolons. Your problem is that you need braces if you want to have more than expression in an if- or else-block.

PS: Note that using a mutable non-local variable to keep track of your state is a bad idea design-wise and will give you trouble if you call your method more than once (without resetting the variable in between).

PPS: You should closely look at what you do when xs.tail is empty. Are you sure that logic is correct?