background preloader

Scala 1

Facebook Twitter

Scala ray. Guido's thoughts on Scala. Many people who have reacted to Guido's gripes with Scala have bent the post towards a static-typing-is-bad-and-dynamic-typing-is-good syndrome. I think the main point of concern that Guido expresses relates to the complexity of Scala's type system and the many exceptions to the rules for writing idiomatic Scala. While it is true that there are quite a few rough edges in Scala's syntax today, none of them look insurmountable and will surely be addressed by the language designers in the versions to come. We need to remember that Scala is still a very much growing language and needs time and community feedback to evolve into one of the mainstream general purpose languages.

As Martin has mentioned elsewhere, Scala's grammar is no bigger than Java, OCaml or C# and hence the language should not impose a more complex mental model for using the same set of features that the other statically typed languages espouse. new Order to buy ( 100 sharesOf "IBM" ) maxUnitPrice 300 using premiumPricing. Equalizer. I wrote a cool Equalizer class in Scala that allows me to do assertions that are more readable than traditional assertions. Quick side note: (Equalizer is really an idea shamelessly stolen from Bill Venners Equalizer in ScalaTest. Hopefully we'll add my methods in as well.) My Equalizer lets me do things like: val x = 5x mustBe 5 This replaces the more common assertEquals( x, 5 ), and I think it does so nicely. You can also do a few more sophisticated things with it, like so: val x = 5x mustBe ( 3 or 4 or 5 ) I probably could have used "in" here, such as x mustBe in( 3, 4, 5 ) ... what do you think?

Additionally: val x = 5x cantBe 6 For whatever this one is worth (I've actually found use cases for it): val x = falsex canBeNullOr false val y = 6y canBeNullOr ( 5 or 6 ) This works by implicitly converting Any to Equalizer, which contains the methods above. Import org.testng.Assert class Equalizer(a: Any) { def cantBe(b: Any) = assertFalse(a == b) def is(b: Any) = a equals b import Equalizer. Using Scala Implicits to Replace Mindless Delegation. I'm still refactoring my Scala CPU Simulator code, as I keep finding ways to just lop off piles of unneeded code. In this latest example, I was using pretty standard Java style delegation - having my class implement an interface, having a member variable of that interface, and delegating all method calls on that interface to the member variable.

There are several problems with this: The main problem: if I add a method to the interface I then have to add it to everyone implementing the interface. But, what If I'm not actually writing the implementation of the interface? Client code won't compile. Adding an implicit doesn't remove this problem entirely, but it certainly works for plain old delegates.It's error prone. Maybe the method was a void, and my IDE added the signature for the method, so the code compiles, but I forgot to actually delegate to the member. First, here is an example of the old, more wordy style: Now for the new version: class DelegateToPowerSource( p: PowerSource ) Refactoring Imperative Code To Functional Code. I've been refactoring Scala literally for days. It's fantastic how much I've learned over the last year. I knew a little bit about functional programming from doing Lisp in college, but a year and a half ago I couldn't have given you the definition of it.

I decided to tackle some of the most obvious (and ugly) imperative/procedural code in my CPU simulator and turn it into an elegant, functional style. I'll paste the original code here, then explain it a bit, then show the refactorings one step at a time. Class EightBitAdder( a: EightBitNumber, b: EightBitNumber, carryIn: PowerSource ) { private val fullAdders: Array[FullAdder] = createFullAdders( a, b, carryIn ) private val output: EightBitNumber = createOutput() def getOutput: EightBitNumber = output def getCarryOut: PowerSource = fullAdders(7).getCarryOut private def createOutput(): EightBitNumber = { val out = new Array[PowerSource](8) Now that we have all the background out of the way, I'll start the refactorings. Simple Refactoring. First Steps to Scala. ScalazineFirst Steps to Scalaby Bill Venners, Martin Odersky, and Lex SpoonMay 9, 2007 Summary In this article, you'll follow twelve steps that are designed to help you understand and gain some basic skills in the Scala programming language.

Scala is a statically typed, object-oriented programming language that blends imperative and functional programming styles. Scala is designed to integrate easily with applications that run on modern virtual machines, primarily the Java virtual machine (JVM). Scala was developed starting in 2003 by Martin Odersky's group at EPFL, Lausanne, Switzerland. One reason you might want to use Scala is that it allows you to increase your productivity compared to Java while leveraging JVM execution speed, your existing investments in Java code, knowledge, and the vast array of APIs available for the JVM.

In Italian, Scala means staircase. To run the examples in this article, you should download Scala from the Scala Downloads page. Scala> 1 + 2 unnamed0: Int = 3 #! Scala. Scala offers a a few powerful abstractions for working with sequences of values. Functional programming style encourages moving from mutable variables and state changes to declarative lists of all known states. Higher order functions like map, flatMap, and filter can very succinctly represent complex requirements.

For example, suppose you were writing a search engine and a user asked for the 10th document about Scala in a database of 10,0000 HTML documents. In a functional style, you might declare the list of all documents, compute the score for each one, and then pick the 10th item. This might look like something like this: documents.filter(isAboutScala)(9) The problem is that if you've got 10,000 big HTML documents, you'll need to first ask each one of 10,000 if they're about Scala to build the filtered list -- only to take the 10th document.

One solution is to use Scala's Stream construct; which is like a List which lazily evaluates the next item only when needed. From Scala to Haskell to Clojure. WarningI'm afraid this entry is going to be more rambling than substance. There are two points on which I do would like to have feedback though. I'll put them in red so you can skip my fool's babbling and get directly to them. ScalaAbout a year ago I got interested in Scala. I bought the Programming in Scala book and begun reading it selectively, concentrating on the functional programming part, something I want to learn. HaskellOne thing led to another, I got introduced to Haskell when I stumbled upon Tony Morris Haskell exercises for beginners. After that, I decided to have a quick look at F#. ClojureThings got quiet for a while until Clojure was mentioned in some article. LispThis is my fourth brushing with Lisp.

I encountered Lisp for the second time about 10 years later on Paul Grahams website. Give & TakeScala & Haskell have a lot of syntax. (Somewhat of a) ConclusionThings have gone full circle now that I'll soon be getting the printed edition of Programming in Scala. /scala/trunk/src/library/scala/xml – Scala – Trac.

Call for maintainers: XML support, bug fixing. Partial functions and Pattern Matching. Scala Constructors. Tonight at BASE, I had a rant about Scala constructors. So I'll just continue the rant here. Constructors seem great in Scala. At first. They give you some great syntactic sugar where it creates accessors/mutators all in one shot: class Stock(val name:String, val symbol:String, var price:Double, var change:Double){} This lets you do nice things like : val stock = new Stock("Apple Computers", "AAPL", 94.77, -1.11)println(stock.symbol) // works greatstock.price = 95 // works good, price is varstock.symbol = "APPL" // won't compile, symbol is a val Yay, no getter/setter garbage.

So in Scala you can do implement the telescoping constructor anti-pattern. Nope, this won't work. Case class Stock(val name:String, val symbol:String, var price:Double, var change:Double){ def this(name:String, symbol:String) = this(name,symbol, 0.0, 0.0) def this(ser:String) = this(parseName(ser), parseSymbol(ser), parsePrice(ser), parseChange(ser)) Oy. Kind of inconsistent, no? Now usage is more uniform: BASE Meeting #7. There was another meeting of the Bay Area Scala Enthusiasts (BASE) at the Mountain View Googleplex yesterday. Last month we met at the Twitter office in San Francisco. Most people seemed happy with this arrangement, so we'll continue alternating meetings between San Francisco and Mountain View, on the second Tuesday of every month, as always. (See the group of the mailing list for more info and reminders.)

Attendance increased a lot from the last time we met in Mountain View; I counted at least 18 people in the room. Bill Venners announced that the Programming in Scala book will be coming back from the printers next week. Dick Wall showed us some Scala code he's been porting from Java. Two interesting issues came up with Dick's code: First, he was a bit dismayed at the lack of flexibility of Scala's Enumerations. Second, with the goal of making his code more functional, he'd made all his classes immutable.

Michael Galpin vented a bit about Scala's constructors and blogged about it later. Scala Type Infix Operators. This post covers an interesting little corner of the Scala syntax: infix operators for types. I missed this corner when I first put together my Scala Syntax Primer. It is not in the "Programming in Scala" book (as of preprint 4), and is hardly mentioned anywhere else. Let's start by backing up a bit and reviewing one of the syntax features of Scala. Scala syntax allows you to use operator characters such as + and * in method names and includes rules allowing you to specify things in a different order using different characters. For example, you could define a right-associative operator ++: on your class Foo, then invoke it on an instance foo of class Foo with an integer argument, putting the instance of the right hand side of the operator because that operator is right-associative (since it ends with a colon): It turns out you can do something similar with types: if you define a higher-kinded type with two type parameters, you can then use that type name as an infix type operator.

Scala as a Scripting Language? 3 Nov 2008 I know, the title seems a bit…bizarre. I don’t know about you, but when I think of Scala, I think of many of the same uses to which I apply Java. Scala is firmly entrenched in my mind as a static, mid-level language highly applicable to things like large-scale applications and non-trivial architectures, but less so for tasks like file processing and system maintenance.

However, as I have been discovering, Scala is also extremely well suited to basic scripting tasks, things that I would normally solve in a dynamic language like Ruby. One particular task which I came across quite recently was the parsing of language files into bloom filters, which were then stored on disk. To me, this sounds like a perfect application for a scripting language. As far as scripts go, this one isn’t too bad. All in all, this script is a fairly natural representation of my requirements.

This is actually runnable Scala. On the readability score, I think Scala wins here too. Meta-Programming with Scala: Conditional Compilation and Loop Un. The kind of comments I keep getting on my static meta-programming with Scala blogs are often along the lines of: “The ability to encode Church Numerals in Scala still seems uselessly academic to me, but cool none-the-less”. In this blog I will show how meta-programming can be applied in practice – at least theoretically. In my previous blogs I introduced a technique for static meta-programing with Scala. This technique uses Scala’s type system to encode values and functions on these values.

The Scala compiler acts as interpreter of such functions. In this post I show how to apply meta-programming for two practical problems: conditional compilation and loop unrolling. Conditional Compilation Conditional compilation is useful for example for enabling or disabling debugging or logging statements. Lets first define meta-booleans and some operations on them (full code here): Using these definitions is quite convenient now: Loop Unrolling Again using this is easy and convenient: Conclusion.

The Scala Experiment: Better Language Support for Component Syst. Is Scala Not “Functional Enough”? 20 Oct 2008 In one of Rich Hickey’s excellent presentations introducing Clojure, he mentions in passing that Scala “isn’t really a functional language”. He says that Java and Scala are both cut from the same mold, and because Scala doesn’t force immutability it really shouldn’t qualify. These viewpoint is something I’ve been hearing a lot of from various sources, people talking about how F# is really the only mainstream functional language, or how once Erlang takes off it will leave Scala in the dust.

When I first heard this sentiment voiced by Rich, I brushed it off as a little odd and only slightly self-serving (after all, if you don’t use Scala, there’s a better chance you will use Clojure). Rich has his own opinions about a lot of things, but I have found with most that I can still understand his rationale, even if I don’t agree. The core of the argument made by Rich (and others) against Scala as a functional language goes something like this: Comparative Type Inference “Now, wait!” No More Statics! Part 2. In a previous post, I explained how Scala's use of singleton objects is better than Java's use of static members.

I was asked for some sample code after that post, so I thought I would throw some together. Let's look at a simple Java class. class Foo { private static int number = 1; public static Foo create(String a) { return new Foo("Some " + a); } private String a; private int id = number++; public Foo(String a) { this.a = a; } @Override public String toString() { return "Foo #" + id + " is " + a; }} This class keeps track of how many instances have ever been created. Scala doesn't have a "static" keyword. Object Foo { var number:Int = 1; def create(a:String) = new Foo("Some " + a)} class Foo(a:String) { private val id:Int = Foo.number Foo.number = Foo.number + 1 override def toString() = { "Foo #" + id + " is " + a }} Because Foo is the name of both an object and a class in the same package, they are allowed to access each other's private members.

Trait Creatable[A] { def create(a:String) : A. Submit a Story to Scala-lang.org! After the recent website redesign, our front page is designed so that it displays updated news items related to the Scala language. However, the stream of stories has been more of a trickle, so far. In order to publish a steady flow of news that is relevant to the entire Scala community, we have therefore decided to open the website to news submissions coming from all Scala users. We are therefore glad to invite news story submissions from the Scala community at large.

Do you have a piece of news that you think may be of interest to the Scala community? We have prepared a new page describing the process in detail: read all about it here. Phasing over from java to scala, retrospect. Real-World Scala: Introduction. Scala Syntax Primer. Scala: The best of both Ruby and Java. The busy Java developer's guide to Scala: Functional progra. Introduction to High-level Programming with Scala. Why Scala? Modelling Game Entities Using Traits. Lazy Functional Queues in Scala. JVM Compiler Construction with Scala and BCEL, Part 1. Writing Scala Compiler Plugins. The Seductions of Scala, Part III - Concurrent Programming. The Seductions of Scala, Part II - Functional Programming. The Seductions of Scala, Part I. So Begins the Functional Revolution. Is Scala Really the Next C++? Return of the Statically Typed Languages. Scala Either. Scala lift-off: Martin Odersky Keynote. Scala: A Scalable Language.

For all you know, it's just another Java library. The busy Java developer's guide to Scala: Of traits and beh. Returning '(()) Considered Difficult. Scala: Still Uncomfortable After Five Years.