scalaloopsscala-option

Option[Int] as index in loop


I am new at Scala so I do not know if I will ask something obvious.

I am currently trying to define a function which can or can not receive a parameter called "position". This parameter is an Int (in case the user decides to pass it). Otherwise, it should be considered as a "None" (because it will mean that nothing has been passed as parameter). If it is a None, then: position = series.length - 1. I am trying to use Option here, since I do not want the user to pass a position if he does not require it.

def example(series: Vector[Double], position: Option[Int]): Vector[Double] = {
  position match {
    case Some(value) =>  value
    case None => series.length - 1
  }
  for (i <- position until series.length) {
    ...
  }
}

But when I try to use it in an loop as an Integer, it gives me an error (Type mismatch. Requiered: CanBuildFrom[Nothing, Int, NotInferedCol[Int]]. Found: Int).

I have been trying different things to make this "position" as an optional value, but I can't figure it out.


Solution

  • The issue in your code is that this:

    position match {
      case Some(value) =>  value
      case None => series.length - 1
    }
    

    is an expression that doesn't mutate the value of position, which is probably what you may have assumed.

    You have to bind the value produced by the expression to use it in the code underneath it:

    val positionWithDefault =
      position match {
        case Some(value) => value
        case None => series.length - 1
      }
    for (i <- positionWithDefault until series.length) {
      ...
    }
    

    Furthermore, as noted in a comment, the behavior of the match expression is the same you'd get out of getOrElse

    for (i <- position.getOrElse(series.length - 1) until series.length) {
      ...
    }