The Artima Developer Community
Sponsored Link

Java Community News
Daniel Spiewak on Idiomatic Scala Features

4 replies on 1 page. Most recent reply: Feb 14, 2008 12:28 AM by Chris McIntosh

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 4 replies on 1 page
Frank Sommers

Posts: 2642
Nickname: fsommers
Registered: Jan, 2002

Daniel Spiewak on Idiomatic Scala Features Posted: Feb 11, 2008 2:14 PM
Reply to this message Reply
Summary
Daniel Spiewak wraps up his mini-tour of Scala, illustrating how to extend classes with implicit type conversions, how to achieve operator overloading in Scala, the benefit of tuples, and Scala's higher-order functions or closures.
Advertisement

While Scala shares many similarities with Java, beyond a certain point the similarities end, and Scala provides powerful, concise solutions to programming problems that Java either does not address, or has much more verbose answers to, according to Daniel Spiewak in the concluding segment of his Scala article series.

In Scala for Java Refugees Part 6: Getting Over Java, Spiewak starts his tour of idiomatic Scala features with the problem of how to extend the functionality of Java classes at runtime:

The basic idea is that classes need not have fixed members, but that methods can be weaved into the class or instance depending on imports. This is similar to the concept of “open classes” supported by highly dynamic languages like Ruby...

As one would expect from a language not tied to such heavy legacy baggage, Scala has managed to solve the problem of class extensions in a very elegant (and type-safe) way... The ultimate answer to the problem of class extensions is…implicit type conversions...

Scala allows you to define methods which take a value of a certain type in as a parameter and return a value of a different type as the result. This in and of itself isn’t so unique until you add the real magic. By declaring this method to be implicit (which is a modifier keyword), you tell the compiler to automatically use this conversion method in situations where a value of type A is called for but a value of type B was passed...

The Scala compiler is also capable of intelligently finding the type you need given the context; more intelligently than just relying on assignment or method parameter type. This is where implicit type conversions become the enabling factor for extension methods.

Another notion Spiewak explains is operator overloading:

Scala ... is really much closer to how mathematicians envisioned operator overloading in Turing-complete languages. The distinction is simple: in Scala, method names can contain arbitrary symbols...

This may seem like a trivial point, but it turns out to be very powerful. One of the leading problems with operator overloading in languages like C++ and Ruby is that you cannot define new operators. You have a limited set of operators with hard-coded call semantics (less-so in Ruby). These operators may be overloaded within carefully defined boundaries, but that’s all. Neither Ruby nor C++ succeed in elevating operator overloading to the level of a generally useful technique...

In Scala, you can call your operators whatever you want because there is no special logic for dealing with them hard-coded into the compiler. Little things like * precedence over + and so on are hard-coded, but the important stuff remains flexible.

Next, Spiewak explains tuples and the ability to return multiple values from a method:

Tuples are fundamentally a way of pairing discrete pieces of data in some sort of meaningful way. Theoretically, they can be applied to many different scenarios such as returning multiple values from a method or examining key-value pairs from a map as a single, composite entity. Really the only thing preventing programmers from exploiting the power of such simple constructs is the lack of an equivalently simple syntax. At least, until now…

Tuples don’t have to be all the same type either... It turns out Scala allows you to put tuples to good use in a lot of ways. For example, returning multiple values from a method...

The final idiomatic Scala technique explained in Spiewak's article is higher-order functions and closures:

[In Java] you can’t just pass a method to another method and expect something to happen (other than a compiler error)... [The] anonymous inner class delegate instance pattern is really like a distant cousin to proper functionals...

Let’s assume for one blissful moment that we could rewrite Swing to take full advantage of Scala’s syntax. Let’s pretend that we changed the addActionListener() method so that it actually would accept a true functional as the parameter, rather than this ActionListener garbage...:

val button = new JButton("Push Me")
button.addActionListener((e:ActionEvent) => {
  println("You pushed me!")
})
add(button)

Instead of a bulky anonymous inner class wrapping around our block of statements, we pass an anonymous method... This method takes a single parameter of type ActionEvent and when called performs a simple println(). It is effectively the same as the Java example, except with one tenth the boiler-plate.

We can actually condense this example down even farther. We can take advantage of some of the flexibility in Scala’s syntax when dealing with function parameters and remove some of those nasty parentheses (after all, it’s Scala, not LISP):

val button = new JButton("Push Me")
button.addActionListener { e:ActionEvent =>
  println("You pushed me!")
}
add(button)

Concise and intuitive, with no nasty surprises like only being able to access final variables (Scala anonymous methods can access any variable/value within its enclosing scope). In fact, what we have here is currently the focus of a great deal of controversy within the Java language community. This, dear friends, is a closure.

What do you think of the Scala features discussed in the article?


Leo Lipelis

Posts: 111
Nickname: aeoo
Registered: Apr, 2006

Re: Daniel Spiewak on Idiomatic Scala Features Posted: Feb 12, 2008 3:09 PM
Reply to this message Reply
On one hand it's nice, but on the other hand, creating a language within a language is not a good idea if you want other people to read what you wrote.

Just use the methods/functions and be done with it. If I was going to indulge in some extremism I would get rid of math operators altogether rather than introduce the ability to make any operator you want.

Not all kinds of flexibilities are good to have in a programming language. A programming language should allow the programmer to feel safe with certain assumptions. Life is hard enough as it is. If you are no longer safe assuming things about common operators, it's not a good thing.

Eivind Eklund

Posts: 49
Nickname: eeklund2
Registered: Jan, 2006

Re: Daniel Spiewak on Idiomatic Scala Features Posted: Feb 13, 2008 8:15 AM
Reply to this message Reply
> On one hand it's nice, but on the other hand, creating a
> language within a language is not a good idea if you want
> other people to read what you wrote.

Well, I agree that if abused, that will make your program unreadable. On the other hand, embedded languages can sometimes make the code much more readable. For instance, using regular expressions instead of writing a parser by hand will generally make things much easier to read - and the benefit of this way of writing things is so large that it offsets the cost of having another miniature language to learn.

And a side thought: Every API is a language, written in a very restricted grammar. The requirement to have this use a restricted grammar is, basically, a lack of trust that the API designer will use sense in exploiting the features available.

Leo Lipelis

Posts: 111
Nickname: aeoo
Registered: Apr, 2006

Re: Daniel Spiewak on Idiomatic Scala Features Posted: Feb 13, 2008 7:09 PM
Reply to this message Reply
> Well, I agree that if abused, that will make your program
> unreadable.

I can see very, very few domains where an embedded language can be useful. For example mathematicians can define math operators for complex math data types. That's fine.

However, for general purpose programming I don't think it's a good idea to grow the language. People should grow libraries instead. Functions should be powerful enough to express anything (like in Scheme). If functions cannot express something that can be expressed by operators, the problem is with functions -- fix them in your language.

I think in general operators should be removed. There should not be any special purpose operators. The more complicated the language definition is, the more potential for misunderstanding. Not to mention that compiler and interpreter writers now have a harder job parsing all the junk.

This is why I like languages like Scheme, Io, Forth, and so on. They have minimal conventions that are leveraged to provide anything you want through libraries. I don't like languages like Perl or Ruby with very intricate definitions for syntax and semantics. To me, allowing a language to overload common operators is like opening the floodgates on a big dam. It's only a matter of time before some fool shoots everyone in the foot.

And ask yourself this: what can you do with overloaded/redefined operators that you cannot do equally or more elegantly using functions in Scheme?

Chris McIntosh

Posts: 4
Nickname: machershel
Registered: Feb, 2008

Re: Daniel Spiewak on Idiomatic Scala Features Posted: Feb 14, 2008 12:28 AM
Reply to this message Reply
> On one hand it's nice, but on the other hand, creating a
> language within a language is not a good idea if you want
> other people to read what you wrote.
Leo, with respect to Daniel's series, it was intended for those (like myself) who are Java developers/architects. The series is excellent from my perspective.

> Just use the methods/functions and be done with it. If I
> was going to indulge in some extremism I would get rid of
> math operators altogether rather than introduce the
> ability to make any operator you want.
Then you are REALLY going to like Scala, which has done just what you're proposing. "Operators" in Scala aren't operators so much as they are (technically) methods defined on objects. As it's defined in the Scala Overview Document (http://www.scala-lang.org/docu/files/ScalaOverview.pdf), "Another aspect of Scala's unified object model is that every operation is a message send, that is, the invocation of a method. For instance the addition x + y is interpreted as x.+(y), i.e. the invocation of the method + with x as the
receiver object and y as the method argument."


> Not all kinds of flexibilities are good to have in a
> programming language. A programming language should allow
> the programmer to feel safe with certain assumptions.
> Life is hard enough as it is. If you are no longer safe
> e assuming things about common operators, it's not a good
> thing.

In Scala, as in Smalltalk, operators are an "illusion." They're simply names of methods.

Flat View: This topic has 4 replies on 1 page
Topic: Scott Davis Introduces Groovy O/R Mapping Previous Topic   Next Topic Topic: A Closer Look at Beans Binding

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use