scalafunctional-programmingmethod-callscala-optionpass-by-name

How would call a function that calls "by-name" as an argument in scala


I'm pretty new to scala and still in the early days of learning. I was reading an article that had an example like so:

def example(_list: List[Positions], function: Position => Option[Path]): Option[Path] = _list match {...}

NB

From what I understand, this method will hold:

and will return Option[Path]

What I don't understand is how are we supposed to call this method?

I tried this:

example(Nil, Option( 0,0 ) )


Solution

  • The type of function is Position => Option[Path] - this is not a by-name argument, it's a type that is equivalent to Function1[Position, Option[Path]] - a function that takes one argument of type Position and returns an Option[Path].

    So, when you call it you can pass an anonymous function with matching type, e.g.:

    example(Nil, pos => Some(List(pos)))
    example(Nil, pos => Some(List()))
    example(Nil, pos => None)
    

    You can also pass a method with matching type, e.g.:

    object MyObj {
      def posToPaths(position: Position): Option[Path] = Some(List(position))
    
      example(Nil, posToPaths)
    }