Scala Action method in Play 2 - scala

I am pretty new to Scala and I am learning Play as well. I see the following construct used in Play
def list = Action {
val products = Product.findAll
Ok(views.html.products.list(products))
}
I am confused as to what
Action {}
does. Is Action the returned value of the method? What is this construct called if I want to know more about it?

This construction called factory method enhanced via scala apply sugar
Action in this reference is the companion object, which could be called singleton, but in fact along with very specific singleton type Action$ it methods reflected as static methods of Action.
As we can read object Action extends ActionBuilder[Request] which have plenty of apply methods constructing values of Action type.
Curly braces here presents nullary function which is null-parameter closure and often named so in different languages like ruby or groovy. It's just multiline block of code which produces something at the end.

Related

How Scala App trait and main works internally?

Hi I'm newbie in Scala.
As far as I know there are 2ways to make entry point in scala, one is define main method with object and the other is extending App trait.
I wondered how App trait works, so I checked the source for App trait, but there are full of confusing code...
The code said that the App has initCodes which are extended from App trait, and these are added in delayedInit method that inherited from DelayedInit. Also the App trait has main method, which will be entry point.
But the What confusing me are
Who call delayedInit? Is it called before the main method is called?(I guess Yes)
Why initCodes is ListBuffer not a element? I think there is only one entry point in application, so I don't think it should be plural.
Where can I check these knowledge? I tried to search in document but I couldn't
Who call delayedInit? Is it called before the main method is called?(I guess Yes)
The delayedInit would be called automatically by the Scala compiler as the initialisation code of the object/class that extends the DelayedInit trait. I expand more on this answer below.
Why initCodes is ListBuffer not a element? I think there is only one entry point in application, so I don't think it should be plural.
Because it is possible to have a hierarchy of classes, where the initialisation code of each class in the hierarchy gets executed as part of executing the program. An example is also provided below.
Where can I check these knowledge? I tried to search in document but I couldn't.
I got to learn about the dynamics by reading the Scala docs and the links it points to. For example this https://github.com/scala/scala/releases/tag/v2.11.0 and https://issues.scala-lang.org/browse/SI-4330?jql=labels%20%3D%20delayedinit%20AND%20resolution%20%3D%20unresolved
I would now try to expatiate more on the answer above by going into more details into the workings of DelayedInit, and how the JVM specifies entry points to programs.
First of all, we have to understand that when Scala is run on the JVM, it still has to adhere to the JVM requirement for defining the entry point to your program, which is to provide the JVM with a class with a main method with signature of public static void main(String[]). Even though when we use the App trait, it might appear as if we are getting away from do this, but this is just an illusion, the JVM still needs to have access to a method with the signature public static void main(String[]). It is just that by extending App together with the mechanism of DelayedInit, Scala can provide this method on our behalf.
Second, it is also good to reiterate that code snippets found in the body of a class (or object) definition, would be the initialisation code of such a class/object and would be executed automatically when such is instantiated. In Java, it is more or less the code you put in the constructor block.
So for a class:
class Foo {
// code.
def method = ???
}
Whatever code is, it will be executed automatically when you call new Foo.
In case of an object
object Foo {
// code.
def method = ???
}
The code will be executed automatically without you having to call new since Scala would automatically make a singleton instance called Foo available for you.
So basically if anything is in the body definition, it gets executed automatically. You do not need to explicitly execute it.
Now to the DelayedInit trait. One thing to be aware of is that it provides us a mechanism to perform what can be called a compiler trick, where certain part of our code gets rewritten. This is one of the reason why it could be confusing to reason about. Because when you use it, what actually gets executed by the Scala compiler is not the code you reading but a slight modification of it. To understand what is going on, you then need to understand the ways the compiler alters the code.
The trick, the DelayedInit trait allows us to perform is to take the code that is part of the body of a class/object definition and turn it, into an argument that is passed by name, to the method delayedInit defined on DelayedInit.
Basically it rewrites this:
object Foo {
// some code
}
into
object Foo {
// delayedInt({some code})
}
This means instead of having // some code executed automatically, delayedInt is the method that is called automatically with // some code passed to it as arguments.
So anything that extends DelayedInit would have its initialisation code replaced by the method call delayedInt with the initialisation code passed as an argument. Hence why nobody needs to explicitly call the delayedInt method.
Now let use see how this then tie to the App trait and how the App trait is used to provide the entry point to a Scala application.
As you will notice, the delayedInit method on the DelayedInit trait does not provide any implementation. Hence the actual behaviour of delayedInit when it is called needs to be provided by something else that extends DelayedInit.
The App trait is such an implementation. And what does the App trait do? Two important thing related to the topic of discussion:
It provides an implementation of delayedInit which takes the initialisation code it is passed, and puts it in a ListBuffer.
It provides the main method def main(args: Array[String]) which satisfy the requirement of the JVM to have a method with public static void main(String[]) to serve as the entry point to a program. And what this main method does, is to execute whatever code placed in the ListBuffer.
The above characteristics of the App trait means that any object/class that extends it would have its initialisation code passed to delayedInit, which would then add it into a ListBuffer, and then the object/class extending it would now have a main method, which when called (most of the time by the JVM as the entry point) would run through the code in the ListBuffer and execute it.
Basically it turns this:
object Foo {
// some code
}
into this
object Foo {
// the implementation of delayedInt is to put `// some code` into a list buffer
delayedInt (// some code)
def main(args: Array[String]) = {
// the implementation below just runs through and execute the code found in list buffer that would have been populated by the call to delayedInt and
???
}
}
So why have a List buffer to store the code to be executed? Because, as I said above it is possible to have a hierarchy of classes, where the initialisation code of each class in the hierarchy gets executed as part of executing the program. To see this in action.
Given the following code snippet:
class AnotherClass {
println("Initialising AnotherClass")
}
trait AnotherTrait {
println("Initialising AnotherTrait")
}
trait YetAnotherTrait {
println("Initialising YetAnotherTrait")
}
object Runner extends AnotherClass with AnotherTrait with YetAnotherTrait with App {
println("Hello world")
}
When run would output the following:
Initialising AnotherClass
Initialising AnotherTrait
Initialising YetAnotherTrait
Hello world
So the individual initialisation code in the hierarchy that consists of AnotherClass, AnotherTrait and YetAnotherTrait gets added to the initCode list buffer, via the delayedInit method of the App trait, and then they get executed by the main method also provided by the App trait.
As you would have noticed by peeking into the source code, the whole mechanism of DelayedInt is deprecated and schedule for removal in the future.
delayedInit:-
The init hook. This saves all initialization code for execution within
main. This method is normally never called directly from user code.
Instead it is called as compiler-generated code for those classes and
objects (but not traits) that inherit from the DelayedInit trait and
that do not themselves define a delayedInit method.
App scala
delayedInit is deprecated since 2.11.0. Also, it has some outstanding bugs which are not fixed.
initCodes:-
I am not sure about the reason for defining the initCodes as ListBuffer.

Quick Documentation For Scala Apply Constructor Pattern in IntelliJ IDE

I am wondering if there is a way to get the quick documentation in IntelliJ to work for the class construction pattern many scala developers use below.
SomeClass(Param1,Parma2)
instead of
new SomeClass(param1,Param2)
The direct constructor call made with new obviously works but many scala devs use apply to construct objects. When that pattern is used the Intelij documentation look up fails to find any information on the class.
I don't know if there are documents in IntelliJ per se. However, the pattern is fairly easy to explain.
There's a pattern in Java code for having static factory methods (this is a specialization of the Gang of Four Factory Method Pattern), often along the lines of (translated to Scala-ish):
object Foo {
def barInstance(args...): Bar = ???
}
The main benefit of doing this is that the factory controls object instantiation, in particular:
the particular runtime class to instantiate, possibly based on the arguments to the factory. For example, the generic immutable collections in Scala have factory methods which may create optimized small collections if they're created with a sufficiently small amount of contents. An example of this is a sequence of length 1 can be implemented with basically no overhead with a single field referring to the object and a lookup that checks if the offset is 0 and either throws or returns its sole field.
whether an instance is created. One can cache arguments to the factory and memoize or "hashcons" the created objects, or precreate the most common instances and hand them out repeatedly.
A further benefit is that the factory is a function, while new is an operator, which allows the factory to be passed around:
class Foo(x: Int)
object Foo {
def instance(x: Int) = new Foo(x)
}
Seq(1, 2, 3).map(x => Foo(x)) // results in Seq(Foo(1), Foo(2), Foo(3))
In Scala, this is combined with the fact that the language allows any object which defines an apply method to be used syntactically as a function (even if it doesn't extend Function, which would allow the object to be passed around as if it's a function) and with the "companion object" to a class (which incorporates the things that in Java would be static in the class) to get something like:
class Foo(constructor_args...)
object Foo {
def apply(args...): Foo = ???
}
Which can be used like:
Foo(...)
For a case class, the Scala compiler automatically generates a companion object with certain behaviors, one of which is an apply with the same arguments as the constructor (other behaviors include contract-obeying hashCode and equals as well as an unapply method to allow for pattern matching).

Scala implicits as explained by Odersky

I'm reading the Odersky book on Scala implicits and I need some help understanding his example. I came across these passages:
Java includes a library named Swing for implementing cross-platform user interfaces. One of the things Swing does is process events from the operating system, convert them to platform-independent event objects, and pass those events to parts of an application called event listeners...
If Swing had been written with Scala in mind, event listeners would probably have been represented by a function type.
What does Odersky mean by function type? I know what event listeners are from writing jQuery and Javascript, but what does he mean by representing event listeners as a function type?
Next, his code examples are a bit unclear to me. The first one:
val button = new JButton
button.addActionListener(
new ActionListener {
def actionPerformed(event: ActionEvent) = {
println("pressed")
}
}
)
So what is going on here? Are we passing an object with a method actionPerformed to the addActionListener method? What is going on here? How would one use this ActionListener?
Next, his reduced Scala friendly code is this:
button.addActionListener(
(_: ActionEvent) => println("pressed")
)
We're passing an anonymous function to the addActionListener method. How would the underscore be used?
Lastly,
implicit def function2ActionListener(f: ActionEvent => Unit) =
new ActionListener{
def actionPerformed(event: ActionEvent) = f(event)
}
So this implicit takes a function that takes in an ActionEvent and returns nothing. What does the new do here? What is it doing? Is it creating a method actionPerformed inside an instantiated object? What is going on?
Since these aren't full code examples, I'm having trouble seeing how they would be used and how it comes together. I'm also a bit lost as to what is going on in the code... like is a new object with a method being defined? Is the actionPerformed method being defined in a new object? Why? Can someone help a bit?
First, you should probably refresh what an anonymous inner class is, and how it is used in Java-centric frameworks for all kinds of callbacks.
What does Odersky mean by function type?
The types of shape (X1, ..., Xn) => Y, implemented by traits
Function1[-X, +Y], Function2[-X1, -X1, +Y] and so on (up to 22 if I remember correctly, unless this restriction has been lifted by now).
what does he mean by representing event listeners as a function type?
"Event listeners" are just special classes that take some kind of Event, and perform some action, usually returning Unit. This is essentially the same as the function type Event => Unit.
What is going on here? How would one use this ActionListener?
As already mentioned above, we are instantiating an anonymous inner class with method actionPerformed, and install it as callback on some GUI-element.
How would the underscore be used?
It isn't used at all. Underscore is specifically for arguments that aren't used. This is because this listener is a bit dumb, and simply prints out the same message every time, regardless of what the event is.
So this implicit takes a function that takes in an ActionEvent and returns nothing.
The instance of the anonymous inner class implementing ActionListener needs the function f to implement the method actionPerformed, and from its signature you can see that it needs Unit as return type, because it just performs some side-effect action when it receives an Event, and doesn't need to return any meaningful values.
By the way: this last implicit conversion is now mostly obsolete because of SAM (single abstract method syntactic sugar).

Understanding Scala Blocks

I'm having difficulty finding specific answers to what I know is something trivial. I would like to understand how blocks work in Scala. I come from a java/ruby background and it seems that scala has an entirely different way of using blocks.
The following code is from the Play! Framework website. I would like to understand what Action is semantically. Is it an object or a function that accepts a block, or perhaps neither.
object Application extends Controller {
def index = Action {
Ok(views.html.index("Your new application is ready."))
}
}
If it is a function, perhaps it's syntactic sugar for the following (in which case how does scala pass around blocks behind the scenes):
def index = Action({
Ok(views.html.index("Your new application is ready."))
})
Or is it some scala syntax I'm unaware of.
Any references to Scala source code would help me understand how this is working behind the scenes.
You would be better to think about scala blocks as java anonymous classes (e.g. like Guava Functions) rather than as ruby blocks. Actually speaking, if you decompile scala code you will see more or less the same code (taken from Guava examples):
Function<String, Integer> lengthFunction = new Function<String, Integer>() {
public Integer apply(String string) {
return string.length();
}
};
The difference is that scala provides a lot of syntax sugar and allows you to write above code as:
val lengthFunction = { string: String => string.length }
As for a specific Action example:
def index = Action({
Ok(views.html.index("Your new application is ready."))
})
Here Action is likely object with apply method. Another scala sugar: language allows you to write Foo(bar) and mean Foo.apply(bar). Next, you can drop round braces when your call isn't ambiguous, so yes, it is actually a method that got called like:
def index = Action({
Ok(views.html.index("Your new application is ready."))
})
And have something like this as a signature:
object Action {
def apply(block: => Result) = ???
}
As already said by #yan, it is scala way to say hey, I'm a function that accept another function that produces Result
Desugared invocation will look like
def index = Action.apply(new AbstractFunction[Result] {
def apply() = Ok.apply(views.html.index.apply("..."))
})
There are a few things going on here. Action is an object which implements an apply() method, what is what gets called when you treat the object as a function. There are a few apply() implementations. The first implementation uses a by-name parameter.
Scala supports a concept known as 'by-name parameters', which are like normal parameters except they are only evaluated when the code that references them is executed. They help with creating constructs which appear like they are part of the language without resorting to macros. In this case, the block surrounding Ok(..) is just a regular block of statements, with the last one's value being used as the value of the block. The example you provided will work as well without the braces. You're essentially just passing the result of Ok's apply method to Action's apply method.
The second version of apply() does indeed take a full anonymous function which maps a Request to a Result. In this case, you can pass an anonymous (or named) function.

Dynamic Proxy using Scalas new Dynamic Type

Is it possible to create an AOP like interceptor using Scalas new Dynamic Type feature? For example: Would it be possible to create a generic stopwatch interceptor that could be mixed in with arbitrary types to profile my code? Or would I still have to use AspectJ?
I'm pretty sure Dynamic is only used when the object you're selecting on doesn't already have what you're selecting:
From the nightly scaladoc:
Instances x of this trait allow calls x.meth(args) for arbitrary method names meth and argument lists args. If a call is not natively supported by x, it is rewritten to x.invokeDynamic("meth", args)
Note that since the documentation was written, the method has been renamed applyDynamic.
No.
In order for a dynamic object to be supplied as a parameter, it'll need to have the expected type - which means inheriting from the class you want to proxy, or from the appropriate superclass / interface.
As soon as you do this, it'll have the relevant methods statically provided, so applyDynamic would never be considered.
I think your odds are bad. Scala will call applyDynamic only if there is no static match on the method call:
class Slow {
def doStuff = //slow stuff
}
var slow = new Slow with DynamicTimer
slow.doStuff
In the example above, scalac won't call applyDynamic because it statically resolved your call to doStuff. It will only fall through to applyDynamic if the method you are calling matches none of the names of methods on the type.