Scala analogue to "with object do begin ... end" (shortcutting method access) - scala

In old rusty Pascal there were convenient construct to perform a sequence of actions on object or record:
with obj do
begin
methodCall
otherMethodCall
...
end
I'm trying to touch something similar in scala, but something missing in my head :)
Is it possible to achieve somehow such effect, as if obj was in current scope of passed closure and behaved as this:
{
import obj._
callObjMethod(x, y)
objVal.doSomething()
...
}
But in customized syntax like:
doWith (obj) {
callObjMethod(x, y)
objVal.doSomething()
}
Intuitionally I feel that it's more no than yes but curiosity wants to know for sure.

Do you mean like this?
val file = new java.io.File(".")
// later as long as file is in scope
{
import file._
println(isDirectory)
println(getCanonicalPath())
}
You can just use the import keyword to bring the methods of the object in scope.

One possibility is the tap method:
def tap[A](obj: A)(actions: (A => _)*) = {
actions.foreach { _(obj) }
obj
}
tap(obj) (
_.callObjMethod(x, y),
_.objVal.doSomething()
)
or after using enrichment
implicit class RichAny[A](val obj: A) extends AnyVal {
def tap(actions: (A => _)*) = {
actions.foreach { _(obj) }
obj
}
}
obj.tap (
_.callObjMethod(x, y),
_.objVal.doSomething()
)
I think that with macros you should even be able to get your desired syntax (and avoid the overhead of creating the function objects), but I'll leave that to someone else.

Related

How to provide implicit argument to code block without explicitly creating it

I have a utility object SideEffects, which is passed to a function as implicit argument. It collects all non-db effects to run if my db transaction was successed.
def someDbAction(implicit se: SideEffects) {
...
se.add {doSomethingNonDbLike()}
...
}
The simple way to use this util is to write something like this:
implicit val se = new SideEffects()
db.run(someDbAction().transactionally).flatMap(se.run)
And I want to write something like this:
SideEffects.run {
someDbAction()
}
Is it possible to do it? Just can't make it work.
I don't understand why your someDbAction (or anything at all for that matter!) needs implicit parameter.
Going by your "I want to write ...", it looks like you want this:
object SideEffects() {
val se = new SideEffects
def run[T](action: => T) =
db.run(action).transactionally.flatMap(se.run())
}
Then SideEffects.run { someDbAction() } (or just SideEffects.run(someDbAction)) does exactly what you wanted.

Anonymous functions with parameters

When you see code that follows this pattern:
def index = Action { request =>
// ..
}
Action trait: https://github.com/playframework/playframework/blob/master/framework/src/play/src/main/scala/play/api/mvc/Action.scala#L65
When looking at this code, how would you know that the request object is available to use within the code block? (is there a intellij shortcut for this?)
Can someone please create a miniature example of where you can mimic this pattern so I can understand how this works, and if you can explain in technical terms what is going on?
The Action trait is not of interest here. Instead, because the body of the index method must be a value, not a type, you are looking at the Action object. You can learn more about objects here. Let's first simplify the syntax by removing syntactic sugar, i.e. making the program behave the same but with simpler constructs. If you try to call an object as if it were a method, what really happens is that .apply is inserted for you by the compiler:
def index = Action.apply((request) => {
// ..
})
This may be more familiar; the apply method is being called on the Action object, passing a lambda function that takes a request. And obviously, an argument to a lambda is always available within that lambda. That's the point of them.
The lambda in this case is also known as a callback. A simple example that clarifies these features follows:
object WithAnswer {
def apply(f: Int => Unit): Unit =
f(42)
}
def printAnswer() = WithAnswer { answer =>
println(answer)
}
This is called as Loan pattern
withWriter creates a writer for the user and then ensures the resource (writer) is properly closely after using.
All that user has to do is just use the writer and write something to the file
def withWriter(file: File)(f: Writer => Unit): Unit = {
val writer = new PrintWriter(file)
try {
f(writer)
} finally {
writer close
}
}
Usage:
withWriter(new File("some_fix.txt") { writer =>
writer println("write something")
}

Chaining logging with a simple expression in Scala

I usually use Scala with SLF4J through the Loggable wrapper in LiftWeb. This works decently well with the exception of the quite common method made up only from 1 chain of expressions.
So if you want to add logging to such a method, the simply beautiful, no curly brackets
def method1():Z = a.doX(x).doY(y).doZ()
must become:
def method1():Z = {
val v = a.doX(x).doY(y).doZ()
logger.info("the value is %s".format(v))
v
}
Not quite the same, is it? I gave it a try to solve it with this:
class ChainableLoggable[T](val v:T){
def logInfo(logger:Logger, msg:String, other:Any*):T = {
logger.info(msg.format(v, other))
v
}
}
implicit def anyToChainableLogger[T](v:T):ChainableLoggable[T] = new ChainableLoggable(v)
Now I can use a simpler form
def method1():Z = a.doX(x).doY(y).doZ() logInfo(logger, "the value is %s")
However 1 extra object instantiation and an implicit from Any starts to look like a code stink.
Does anyone know of any better solution? Or maybe I shouldn't even bother with this?
Scala 2.10 has just a solution for you - that's a new feature Value Class which allows you to gain the same effect as the implicit wrappers provide but with no overhead coming from instantiation of those wrapper classes. To apply it you'll have to rewrite your code like so:
implicit class ChainableLoggable[T](val v : T) extends AnyVal {
def logInfo(logger:Logger, msg:String, other:Any*) : T = {
logger.info(msg.format(v, other))
v
}
}
Under the hood the compiler will transform the logInfo into an analogue of Java's common "util" static method by prepending your v : T to it's argument list and updating its usages accordingly - see, nothing gets instantiated.
That looks like the right way to do it, especially if you don't have the tap implicit around (not in the standard library, but something like this is fairly widely used--and tap is standard in Ruby):
class TapAnything[A](a: A) {
def tap(f: A => Any): A = { f(a); a }
}
implicit def anything_can_be_tapped[A](a: A) = new TapAnything(a)
With this, it's less essential to have the info implicit on its own, but if you use it it's an improvement over
.tap(v => logger.info("the value is %s".format(v)))
If you want to avoid using implicits, you can define functions like this one in your own logging trait. Maybe not as pretty as the solution with implicits though.
def info[A](a:A)(message:A=>String) = {
logger.info(message(a))
a
}
info(a.doX(x).doY(y).doZ())("the value is " + _)

How are "Closures" such a powerful abstraction that object systems and fundamental control structures are implemented using it?

Here is a quote from programming scala chapter 1:
Closures are such a powerful abstraction that object systems and fundamental control structures are often implemented using them
Apparently the statement is not specifically about Scala but Closures in general but I can not
make much sense from it. Perhaps it is some pearl of wisdom only meant for those mighty compiler writers!
So who uses Closures to implement fundamental control structures and why?
Edit: I remember reading something about custom control structures in groovy "using the closure as the last parameter of method call" syntax and making the structure available to your code using meta-classes or use keyword with Categories. Could it be something related?
Edit: I found the following reference of the groovy custom control structures syntax here (slide 38):
Custom control structures
Thanks to closures
When closures are last, they can be put “out” of the parentheses
surrounding parameters
unless(account.balance > 100.euros, { account.debit 100.euros })
unless(account.balance > 100.euros) { account.debit 100.euros }
Signature def unless(boolean b, Closure c)
Apparently what groovy is offering is a syntactic sugar for making the Closure based custom control structures appear like first-class control structures offered by the language itself.
I commented on the case of control structures. Let me comment on closures as objects. Consider what happens when you call a method on an object; it has access not only to the argument list, but also the fields of the object. That is, the method/function closes over the fields. This isn't that different from a "bare" function (i.e., not an object method) that closes over variables in scope. However, the object syntax provides a nice abstraction and modularity mechanism.
For example, I could write
case class Welcome(message: String) {
def greet(name: String) = println(message + ", " + name)
}
val w = Welcome("Hello")
w.greet("Dean")
vs.
val message = "Hello"
val greet = (name: String) => println(message + ", " + name)
greet("Dean")
Actually, in this example, I could remove the "case" keyword from Welcome, so that message doesn't become a field, but the value is still in scope:
class Welcome2(message: String) { // removed "case"
def greet(name: String) = println(message + ", " + name)
}
val w = new Welcome2("Hello") // added "new"
w.greet("Dean")
It still works! Now greet closes over the value of the input parameter, not a field.
var welcome = "Hello"
val w2 = new Welcome2(welcome)
w2.greet("Dean") // => "Hello, Dean"
welcome = "Guten tag"
w2.greet("Dean") // => "Hello, Dean" (even though "welcome" changed)
But if the class refers to a variable in the outer scope directly,
class Welcome3 { // removed "message"
def greet(name: String) = println(welcome + ", " + name) // reference "welcome"
}
val w3 = new Welcome3
w3.greet("Dean") // => "Guten tag, Dean"
welcome = "Buon giorno"
w3.greet("Dean") // => "Buon giorno, Dean"
Make sense?
There are three fundamental control structures:
Sequence
a = 1
b = 2
c = a + b
Conditions
if (a != b) {
c = a + b
} else {
c = a - b
}
Iterations/loops
for (a <- array) {
println(a)
}
So, I guess they mean that internally many languages use closures for control structures (you can look the last two structures).
As an example:
if (a < b) {
for (i = a; a < b; a++) {
println(i)
c = i * i
}
} else {
c = a - b
}
So for is a closure inside the if closure, and else is a closure too. That's how I understand it. They create a closure for the first if if the condition is true, create the closure inside the braces, call it. Then create a closure for the for loop and call it while the condition is true.
And I guess there is no list of languages which use closures internally.
Update:
Just as an example, this is how you can implement your own for loop in Scala (o is cyrillic, so it will compile):
def fоr(start: Unit, condition: => Boolean, increment: => Unit)(body: => Unit): Unit = {
if (condition) {
body
increment
fоr(0, condition, increment)(body)
}
}
var i = 0
fоr (i = 0, i < 1000, i += 1) {
print(i + " ")
}
So actually this is how it can be implemented in other languages on the inner level.
I would say that "closures are such a powerful abstraction..." because unlike standard methods, you have a reference to the calling object, regardless of the scope in which the closure has been called.
In Groovy, for example, you can add a new method, "capitalize" to String type:
String.metaClass.capitalize = {
delegate[0].upper() + delegate[1..-1].lower()
}
"hello".capitalize() // "Hello"
Or, you can do something more complex, like create a domain specific language (DSL) using closures.
class ClosureProps {
Map props = [:]
ClosureProps(Closure c) {
c.delegate = this // pass closure scope to "this"
c.each{"$it"()} // iterate through closure, triggering missingMethod()
}
def methodMissing(String name, args) {
props[name] = args.collect{it} // collect extracted closure properties
}
def propertyMissing(String name) {
name
}
}
Example
class Team {
// the closure
static schema = {
table team
id teamID
roster column:playerID, cascade:[update,delete]
}
}
def c = new ClosureProps(Team.schema)
println c.props.id // prints "teamID"
a) Please try at least googling topics before asking questions.
b) Once you have done that, please ask specific questions.
c) Lexical closures are functions that have access to a lexical environment not available where they are invoked. As such, their parameters can be used to select messages, and pass parameters with those messages. For general control structures, they are not sufficient, unless they can affect the call stack, in the manner of continuations.

Scala DSL without extra syntax

I asked myself this question a couple of times and came up with a solution for that feels very dirty. Maybe you can give me any advice since I think this is a basic problem for every DSL written in Scala.
I want to have a hierarchical structure of nested objects without adding any extra syntax. Specs is a good example for this:
MySpec extends Specification {
"system" should {
"example0" in { ... }
"example1" in { ... }
"example2" in { ... }
}
"system" can {
"example0" in { ... }
}
}
For instance I do not have to write "example0" in { ... } :: "example1" in { ... } :: "example2" in { ... } :: Nil.
This is exactly the same behaviour I would like to have. I think this is achieved by an implicit definition in the Specification class in Specs like (please do not be offended if you are the Specs author and I missunderstood something :))
implicit def sus2spec(sus: Sus): Specification = {
suslist += sus
this
}
My main problem arises now when I want to nest such objects. Imagine I have this grammar:
root: statement*;
statement:
IDENT '{' statement* '}'
| declaration*
;
declaration: IDENT ':=' INT+;
I would like to translate this into a DSL that looks like this:
MyRoot extends Root {
"statement0" is {
"nested_statement0" is {
"nested_nested_statement0" is {
"declaration0" := 0
}
"declaration1" := 1
"declaration2" := 2
}
"declaration3" := 3
}
"statement1" is {
"declaration4" := 4
}
}
The problem that arises here is for me that the implicit solution does not work. The implicit definition would be executed in the scope of the root object which means I would add all objects to the root and the hierarchy is lost.
Then I thought I can use something like a Stack[Statement]. I could push an object to it for every call to is but that feels very dirty.
To put the question in one sentence: How do I create a recursive DSL wich respect to its hierarchy without adding any extra syntax and is there a solution to do this with immutable objects only?
I've seen a nice trick in XScalaWT to achieve the nesting in DSL. I didn't check if specs uses the same, or something different.
I think the following example shows the main idea. The heart of it is the setups function: it accepts some functions (more precisely closures, if I'm not mistaken) that needs only a Nestable and will call them on the current one.
printName happens to be such a method, just like addChild, with parameters filled for the first list of params.
For me understanding this was the revealing part. After that you can relatively simply add many other fancy features (like implicit magic, dsl methods based on structural typing, etc.).
Of course you can have any "context like" class instead of Nestable, especially if you go for pure immutable stuff. If parents need references to children you can collect the children during the setups() and create the parent only at the end.
In this case you would probably have something like
private def setupChildren[A, B](a : A, setups:(A => B)*) : Seq[B] = {
for (setup <- setups) yield setup(a)
}
You would pass in the "context", and create the parent using the returned children.
BTW I think this setup thing was needed in XScalaWT because it's for SWT where child objects need a reference to their parent control. If you don't need it (or anything from the current "context") then everything becomes a bit easier.
Using companion objects with proper apply methods should mostly solve the problem. Most likely they should also accept other functions, (having the same number of params, or a tuple if you need more).
One disadvantage of this trick is that you have to have a separate dsl method (even if a simple one) for each method that you want to call on your classes. Alternatively you can use lines like
x => x.printName
which will do the job, but not so nice (especially if you have to do it often).
object NestedDsl {
object Nestable {
def apply(name: String, setups:(Nestable => Unit)*): Nestable = {
val n = new Nestable(None, name)
setup(n, setups: _*)
n
}
}
class Nestable(parent: Option[Nestable], name: String) {
def printName() { println(name) }
}
// DSL part
def addChild(name: String, setups:(Nestable => Unit)*)(parent: Nestable) = {
val n = new Nestable(Some(parent), name)
setup(n, setups: _*)
n
}
def printName(n: Nestable) = n.printName
private def setup[T](t : T, setups:(T => Unit)*) : T = {
setups.foreach(setup => setup(t))
t
}
def main(args: Array[String]) {
Nestable("root",
addChild(
"first",
addChild("second",
printName
)
)
)
}
}
I have had a look at specs and they do not do it any differnet. Basically all you need is a mutable stack. You can have a look at the result here: cssx-dsl
The code is quite simple. Basically I have a mutable builder and convert it to an immutable representation afterwards.