I am an new learner of scala, and i am trying to run this sample code
def isLast(c: Int, r: Int):Int ={ if(r == 1) { return 1; } else if (r == c){ return 1 } }
But it gives me compile time error, saying
Multiple markers at this line - type mismatch; found : Unit required: Int - type mismatch; found : Unit required: Int
Kindly help me, and also suggest me some good site for learning scala.
Syntax. if(Boolean_expression 1){ //Executes when the Boolean expression 1 is true } else if(Boolean_expression 2){ //Executes when the Boolean expression 2 is true } else if(Boolean_expression 3){ //Executes when the Boolean expression 3 is true } else { //Executes when the none of the above condition is true. }
Like many other applications and programming languages, Scala also has a decision making conditional if-else statements. The if statement conditional block is executed if the condition is found to be True, if not then the else conditional block is implemented (only if, else statement is present).
Scala IF Statement The syntax of Scala if statement is if(boolean_expression) { // statements inside if block } Scala if statement contains an if keyword followed by a boolean expression. If the boolean expression evaluates to true, then the statements inside the if block are executed.
In scala, functions are first class values. You can store function value, pass function as an argument and return function as a value from other function. You can create function by using def keyword. You must mention return type of parameters while defining function and return type of a function is optional.
First, let's clean up your code a little:
def isLast(c: Int, r: Int):Int = { if(r == 1) return 1 else if (r == c) return 1 // but what about when r is neither 1 nor c ?? }
So you are telling scala that if r
is 1, then return 1, and if r == c
, return 1. That's fine. But if you want the method to return an Int, it has to return one in every case. So Scala complains because it doesn't know what Int to return when r
is neither 1 nor c
.
The fix is to add an else
clause than returns some other Int.
As an additional note, you can and should leave out the return
keyword here, letting Scala implicitly know that the result of the if-else expression, as the last expression in the function's body, should be returned:
def isLast(c: Int, r: Int):Int = { if(r == 1) 1 else if (r == c) 1 else 0 // or some other Int }
As a final note, if you have a function whose name starts with is
, then it should probably return a Boolean. In other words, if the input is last, then return true, otherwise false.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With