Goldengirl
Goldengirl

Reputation: 967

How do I return a value from a scala function?

I am fairly new to scala and was trying out a few simple things. I created a function that looks something like this:

 private def checkValu() : Option[Integer] = {
    if(!list.isEmpty()){
        for(value <-list){
            val x = list.get(0)
        }
    }
    return (x)
  }

I call the function in order to return the value x.I access the value of the list and want to return the first value in the list. But somehow this does not seem to work. It gives me an error saying

"not found value x". 

I also tried doing without the "return" statment, but then it gives me errors at the if and for loop saying

"type mismatch; found : Unit required: Option[Integer]"

What am I missing here? Could seombody please help me here.

Thank you in advance.

Upvotes: 0

Views: 610

Answers (2)

Gorazd
Gorazd

Reputation: 21

Wouldn't this be easier:

def checkValue(): Option[Int] = list.headOption 
// assuming list is List[Int] and you want to return option of the first element 

Upvotes: 2

G&#225;bor Bakos
G&#225;bor Bakos

Reputation: 9100

I guess you are looking for something like this:

 def checkValue() : Option[Integer] = {
    if(!list.isEmpty()) {//Assuming list is java.util.List[Integer] and want the last value
        return Some(list.get(list.size() - 1))
    }
    None
 }

This solution uses java.util.List<Integer>, I guess you used that for list. None is simply returned when no values are present, otherwise, the last, though I was not sure that was your intention, in case you want the first: return Some(list.get(0))

A more idiomatic solution:

 def checkValue() : Option[Integer] = {
    if(!list.isEmpty()) {//Assuming list is java.util.List[Integer] and first value is required
        Some(list.get(0))
    } else {
        None
    }
 }

I was unsure which value you wanted to return because you wanted to loop through the whole list (naming of the method did not help either). Probably @cmbaxter was right and you wanted the first one.

Just some notes about the error messages: first: you were referring to a variable x that was out of scope (outside of the for comprehension), so it was not a good choice. The second one was probably caused by because of the if statement without else, which results in Unit. As that remain the only expression, that was tried to be returned, though that was not an Option[Integer].

Upvotes: 3

Related Questions