-3

i'm new to Scala and try to work with Options but somehow i still have to set a return value for my method to work. It*s not clear to me why. The code below gets a path parameter that points to a csv file. I want one line of the csv file to be the attributes of an object. Comment shows the problematic line:

import io.Source

case class Example(attribute1: Int, attribute2: Int)

object Example {
  def apply(path: String, value1: Int): Option[Example] = {
    for {
      line <- Source.fromFile(path).getLines()

      if line.replaceAll(" ", "").startsWith(value1 + ";")

      param = line.split(";")
    } {
      Some(Example(value1, param(1).toInt))
    }

    // Why this line??
    return None
  }
}
pnuts
  • 58,317
  • 11
  • 87
  • 139
  • possible duplicate of [Return in Scala](http://stackoverflow.com/questions/12560463/return-in-scala) – cchantep Apr 29 '15 at 21:15

1 Answers1

1

If the intent is to find the first occurence of value1 (if it exists) this would do the trick:

object MaintenanceRequest {
  def apply(path: String, value1: Int): Option[Example] =

  // get all lines
    Source.fromFile(path).getLines()

      // find the first line that matches value1
      .find(_.replaceAll(" ", "").startsWith(value1 + ";"))

      // map over the match if found
      .map { line =>

      // convert the matched line into Example
      val param = line.split(";")
      Example(value1, param(1).toInt)
    }
}

Basically you are trying to find the first match which returns an Option[String]. Calling map on an option will let you change the type of the Some variant, while leaving the None alone, which lets us convert Option[String] to Option[Example]

Arne Claassen
  • 14,088
  • 5
  • 67
  • 106
  • value1 is like a key for the data records in the csv, so i want to return only one object of Example like the signature of the method says –  Apr 29 '15 at 21:02
  • okay, got it : http://stackoverflow.com/questions/13343531/how-to-yield-a-single-element-from-for-loop-in-scala –  Apr 29 '15 at 21:20