Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

purpose of scala type (=> A) => O

Tags:

scala

I found a strange type in this code on github:

  final class StaticRouteB[Page, O](private val f: (=> Action[Page]) => O) extends AnyVal {
    def ~>(a: => Action[Page]): O = f(a)
  }
  1. The type of f. What does it mean ? My guess is that it is a function with a call by name argument. Never seen it before, so I am not sure what it is or how does this thing work.

  2. Is there a way to translate this type into something more "standard" ? (The code above I mean, so that it does not use the (=> Action[Page]) => O) type ? Is this type just some syntactic sugar ?)

  3. I wonder especially, what happens if I pass Action[Page] => O as f when creating StaticRouteB ? Will I get a compile error ? Run time error ? Why ? I mean, what is the purpose of (=> ... ) ? Is it to give a compile error if not the right kind of function is passed or to change the evaluation strategy of f's parameters ? I mean why would anyone want to have a type like this ? For what purpose?

like image 499
jhegedus Avatar asked Mar 10 '23 10:03

jhegedus


1 Answers

(=> Action[Page]) is a "call by name" parameter.

So f: (=> Action[Page]) => O is a function with a call by name parameter of type Action[Page], and this function returns result of type O.

You can see its usage in a method ~> definition.

like image 186
Tyth Avatar answered Mar 30 '23 12:03

Tyth