Kacy Kacy - 1 year ago 84
Scala Question

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 {...}


  • Position is a

  • Path is a
    List( Position )

From what I understand, this method will hold:

  • list of positions

  • Option[Path]

and will return

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

I tried this:

example(Nil, Option( 0,0 ) )

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download