ashutosh raina
ashutosh raina

Reputation: 9314

Returning in a Scala For loop

I am new to Scala so trying to do the simple thing first.

I wrote a method which is below.

//Given a list of numbers find the first number that is a multiple of 7
  def FindFirstMultiple(input: List[Int]) : Int  = {   
    for (
        i <- input        
        if (i % 7 == 0)
       ) 
      return i        
  }  

This method gives error

type mismatch;  found   : Unit  required: Int   

I am not able to comprehend this. When I don't have a return type and just print the values, it works fine. Also, Why does the error squiggly hover over i <- input. I think the Scala compiler is trying to tell me something, and I just can't understand it. What would be the cause of this error ?

Upvotes: 1

Views: 2687

Answers (2)

Arnon Rotem-Gal-Oz
Arnon Rotem-Gal-Oz

Reputation: 25909

If you want to run this with a for loop you need to also add a return 0 as in

def FindFirstMultiple(input: List[Int]) : Int  = {   
    for ( i <- input if (i % 7 == 0)) return i 
    0       
  }  

The end value is needed as the for itself doesn't return anything when the if isn't satisfied.

As user1779032 suggested a better way is

def FindFirstMultiple(input: List[Int]) = input.find(i => i % 7 == 0).getOrElse(0)  

Upvotes: 5

user1779032
user1779032

Reputation: 496

for in Scala is not a for loop, in fact it's not a loop at all. It's a syntactic sugar for map and flatMap and other monadic goodies. Monads are very useful in functional programming, i recommend invest some time learning them; you can start at http://james-iry.blogspot.com/2007/09/monads-are-elephants-part-1.html , follow the whole series. Thanks to the wonderful Mr James Iry.

If you just want the first item that matches your query, try this

val findFirst:Option[Int] = input.find(i => i % 7 == 0)

Posible values for findFirst are

  1. Some(n) if something was found, where n is the Int found
  2. None if nothing was found

Upvotes: 2

Related Questions