Reputation: 31
I wrote the following simple code:
def Commas(n: Long) = {
if (n >= 1000)
Commas(n/1000)
print(","+ n%1000/100 + n%100/10 + n%10)
else
print(n%1000/100 + n%100/10 + n%10)
}
While it seems correct to me, there is an error. What is wrong with the above code?
Upvotes: 3
Views: 4688
Reputation: 1548
Disclaimer: This solution is for the similar error but not the same situation.
I have faced the same error. The mistake I did was, I copy pasted the command prompt code to file and forget to remove the pipe (|) character in the lines for the function and got the same error. If you come to this page due to that reason, now you can fix it. Enjoy.
Upvotes: 1
Reputation: 955
The If...else...
syntax expects a statement. You can use a surrounding code block to ensure your code works as expected. Something like(also note that you have to specify return type to Unit
or just remove the =
sign):
def Commas(n: Long) {
if (n >= 1000) {
Commas(n/1000)
print(","+ n%1000/100 + n%100/10 + n%10)
}
else
print(n%1000/100 + n%100/10 + n%10)
}
Upvotes: 5
Reputation: 1266
Try this:
def Commas(n: Long) = {
if (n >= 1000) {
Commas(n/1000)
print(","+ n%1000/100 + n%100/10 + n%10);
}
else {
print(n%1000/100 + n%100/10 + n%10);
}
Upvotes: 1
Reputation: 8378
While, you've got two solutions on how to fix it, here's why it is not working as you expect it to: Conditional expressions in scala expect expressions in their if
and else
blocks. There are several ways to make several expressions (like you have there) into one compound expression (and you can see examples of those in other answers to your question).
Upvotes: 0
Reputation: 11
Or try this:
def Commas(n: Long) = {
if (n >= 1000)
Commas(n/1000); print(","+ n%1000/100 + n%100/10 + n%10)
else
print(n%1000/100 + n%100/10 + n%10)
}
Upvotes: -1