Scala implicits as explained by Odersky - scala

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).

Related

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).

Use mocked function return value in real function call

Is it possible to use a mocked function inside a real function call? Both functions are in the same object. So for example, if I have
obj A {
def mockThis(value: Int): Int = {
value*5
}
def realFuncIWantToTest(value: Int): Int = {
val v = mockThis(value)
v
}
}
Obviously this is an extremely simple case and this isn't what my code is doing (v is actually a complicated object). Essentially I want realFuncIWantToTest to use the mocked function return value that I define.
Thanks!
You might be able to do this using Mockito's spies; see here for an example on that.
Spies basically work by having that spy wrapping around a real object of your class under test.
But one word here: even when it is possible, please consider changing your design instead. This "partial mocking" is often a good indication that your class is violating the single responsibility principle. Meaning: a class should be responsible for "one" thing. But the idea that you can / have to partially mock things within your class indicates that your class is responsible for at least two, somehow disconnect aspects.
In that sense: the better approach would be that mockThis() would be a call on another object; which could be inserted via dependency injection into this class.
Long story short: at least on a Java level your idea should work fine (where I have certain doubts that Mockito will work nicely with your scala objects) from a technical perspective; but from a conceptual point point; you should rather avoid doing it this way.

Calling type-specific code from a library function, determined at compile-time

How can you make code in a Scala library call type-specific code for objects supplied by a caller to that library, where the decision about which type-specific code to call is made at compile-time (statically), not at run-time?
To illustrate the concept, suppose I want to make a library function that prints objects one way if there's a CanMakeDetailedString defined for them, or just as .toString if not. See nicePrint in this example code:
import scala.language.implicitConversions
trait CanMakeDetailedString[A] extends (A => String)
def noDetailedString[A] = new CanMakeDetailedString[A] {
def apply(a: A) = a.toString
}
object Util {
def nicePrint[A](a: A)
(implicit toDetail: CanMakeDetailedString[A] = noDetailedString[A])
: Unit = println(toDetail(a))
def doStuff[A](a: A)
: Unit = { /* stuff goes here */ nicePrint(a) }
}
Now here is some test code:
object Main {
import Util._
case class Rototiller(name: String)
implicit val rototillerDetail = new CanMakeDetailedString[Rototiller] {
def apply(r: Rototiller) = s"The rototiller named ${r.name}."
}
val r = Rototiller("R51")
nicePrint(r)
doStuff(r)
}
Here's the output in Scala 2.11.2:
The rototiller named R51.
Rototiller(R51)
When I call nicePrint from the same scope where rototillerDetail is defined, the Scala compiler finds rototillerDetail and passes it implicitly to nicePrint. But when, from the same scope, I call a function in a different scope (doStuff) that calls nicePrint, the Scala compiler doesn't find rototillerDetail.
No doubt there are good reasons for that. I'm wondering, though, how can I tell the Scala compiler "If an object of the needed type exists, use it!"?
I can think of two workarounds, neither of which is satisfactory:
Supply an implicit toDetail argument to doStuff. This works, but it requires me to add an implicit toDetail argument to every function that might, somewhere lower in the call stack, have a use for a CanMakeDetailedString object. That is going to massively clutter my code.
Scrap the implicit approach altogether and do this in object-oriented style, making Rototiller inherit from CanMakeDetailedString by overriding a special new method like .toDetail.
Is there some technique, trick, or command-line switch that could enable the Scala compiler to statically resolve the right implicit object? (Rather than figuring it out dynamically, when the program is running, as in the object-oriented approach.) If not, this seems like a serious limitation on how much use library code can make of "typeclasses" or implicit arguments. In other words, what's a good way to do what I've done badly above?
Clarification: I'm not asking how this can be done with implicit val. I'm asking how you can get the Scala compiler to statically choose type-appropriate functions in library code, without explicitly listing, in every library function, an implicit argument for every function that might get called lower in the stack. It doesn't matter to me if it's done with implicits or anything else. I just want to know how to write generic code that chooses type-specific functions appropriately at compile-time.
implicits are resolved at compile time so it can't know what A is in doStuff without more information.
That information can be provided through an extra implicit parameter or a base type / interface as you suggested.
You could also use reflection on the A type, use the getType that returns the child type, cast the object to that type, and call a predefined function that has the name of the type that writes the string details for you. I don't really recommend it as any OOP or FP solution is better IMHO.

Scala Action method in Play 2

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.

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.