background preloader

Scala 2

Facebook Twitter

Making SWT shine with Scala. At Agile 2008 I was calmly coding together with Daniel Brolund in the open space area. We were interrupted by a guy that asked us if we did any coding in Ruby and if we did he will hold a lightning-talk about a framework he had put together to create SWT-gui:s using JRuby. Interestingly enough I had thought about how GUI-coding could probably be improved in a language such as Ruby so I reluctantly stopped what I was doing and watched the lightning talk. This was the first time I ever saw Glimmer and it totally blew me away! It must be possible to do in Scala! I had already started playing with Scala and I thought it would be a cool experiment to see if I could do something similar in Scala. After all, scala is a pretty expressive language. I made the first attempt a few months ago and I think that qualifies as a failure. I showed what I did to colleague and I got some pointers on how to make my code more function-oriented and hence get rid of some redundancy and mutable state.

Success! Comparing Manifests. Higher-Order Fork/Join Operators. 22 Sep 2008 I think we can all agree that concurrency is a problem. Not really a problem as in “lets get rid of it”, but more the type of problem that really smart people spend their entire lives trying to solve. Over the years, many different solutions have been proposed, some of them low-level, some more abstract. However, despite their differences, a common thread runs through all of these ideas: each of them attempts to ease the pain of decomposing operations in a reorderable fashion.

Surprisingly, the word “ordering” is not often heard in conjunction with parallelism. By the way, I really will get to fork/join a little later, but I wanted to be sure that I had laid a solid groundwork for the road ahead. Factorial One of the odd things about computer science is a depressing lack of imaginative examples. For each number, this function performs a number of discrete operations. All this may seem extremely pedantic but please, bear with me. The answer is quite obviously “of course not”. How packages work in Scala. Every now and then someone discovers how packages work in Scala. This process typically passes through a number of stages. Confusion: “Hey, guys, I found this weird bug. Can you take a look?” Surprise: “What? It works like that? Really?” Denial: “No, I don’t believe you. Not everyone reaches step 5. This behaviour is particularly unfortunate because actually Scala’s package behaviour is quite nice. And so, in the hopes of dispelling some of this confusion, I bring to you the reality of how packages work in Scala.

Identifiers You have a bunch of identifiers in scope. Package foo; object bar; object baz{ val kittens = "kittens"; } within this file, say within the object bar, we’ve got a bunch of identifiers in scope: We have foo, the package we are in, bar, an object, and baz, another object. Within the object baz, everything in scope at the outer level is in scope here, but we’ve introduced the additional identifier kittens. Note that a package conceptually constitutes one “level”. Members. Code:simplifying-jdbc [Scala Wiki] The Artima Developer Community. A growing collection of resources on the Scala compiler. Scala: Bringing Future Languages to the JVM. Scala vs Clojure — Round 2: Concurrency! The time for ignoring concurrency has almost passed. If you read my last post you'll know that I'm looking at Scala Vs Clojure and a big part of both of these languages is their support for concurrency.

Scala uses an Erlang inspired actor model, which is a distributed approach to concurrency. Clojure on the other hand leans on it's STM, a non-distributed approach - Lets put them in the ring together! The goal My last post sparked heavy debate in the #scala camp, wherein many frustrations and concerns were expressed by the Scala community. The problem An old concurrency problem/exercise is 'The sleeping barber' and you can either read the full definition here or read my shorter version here: We simulate a barber-shop with 1 barber, 3 waiting chairs and 1 chair for haircutting.The barber sleeps between customers and is thus awoken when one enters the shop. This is a perfect problem for comparing these two languages for the following reasons Actors scala> Redford ! Software Transactional Memory. Strict Ranges? Note: This article was created before Scala 2.8.0 was out, and is mostly related to a problem that is no longer present as of that version.

The code in here is supposed to be run on Scala 2.7.x unless otherwise noted, and the output of Scala 2.8.0 usually refers to some work-in-progress version of it, not the final version.A common mistake newcomers to Scala usually make is to treat Scala ranges as strict. It's easy to see why they make such mistake, because the very expression "strict", though relatively easy to find in the Scala API documentation, is unfamiliar to them. So, before getting into the problem, I'll make a brief detour. In functional languages, there is a concept of "strict functions" and "non-strict functions". Informally, a "strict function" is one which always evaluates its argument. For programmers from a non-functional background, that's most of the functions they ever saw, but not all. 01.scala> object X { 02.| val x = -10 to 10 map (2 / _) 04.defined module X 16.at Y$.

Secret Agents in Scala. Best practices ? I'm actively looking for best practices and patterns about how to create clone objects in Scala, with the possibility to change some values of the cloned object along the way. I have the usual concern of the Java world on that topic: I would like to avoid Java "clone", I want to be able to use the pattern in a class hierarchy, I want to have the minimum amount of code (or at least, the simplest possible) to write in domain class to support my cloning API.

And as I'm in Scala, I want to deal with both vars and vals, if possible in the same consistent way. Actually, I want to provide to my libraries consumer an effective way to do things like that (where *Child* extends *Parent* class): As Scala 2.8 is advertised with "default and named arguments", such things should possible (well, hopefully easy too ;). I came with this solution: That solution seems to work, and allows to do the kind of use case I wanted to build. 3/ and 4/ are just feelings, and so could be shut up for now.

Scala Vs Clojure – Let's get down to business. Scala closures as poor man's mocks. Groovy has this feature that you can use a closure whenever you need an interface with one method only. A class implementing the interface is automatically created, and the closure provides the implementation of this single method. This process is called closure coercion and is particularly convenient to make tests readable and concise. I'm not yet sure about the relative advantages of such code everywhere, since there might be ambiguities or the intent might be obscured. Tests usually contain a lot of boilerplate, though, so I'm all for making them more concise. Except for readability, people would be more likely to write a test if it doesn't take much effort to create yet another trivial mock. Who tests your tests though? You don't need to answer. In Scala there are implicit conversions, which help define a controlled way to coerce a value to a different type.

Import java.nio.CharBuffer Compare this with the Groovy version: Type-safe printf in scala ‽ All the excitement surrounding Scala's next big release - 2.8.0 - reminds me of another big release a few years ago. Java 5 was poised to be a huge leg up for developers, long feature lists were all over the java blogosphere: generics, enums, enhanced for-loops, autoboxing, varargs, util.concurrent, static imports, and so on; in sum, a whole heap of goodness. But there were a few odd ducks hidden in the feature lists, most notably "an interpreter for printf-style format strings". Anyone who has been around curly-brace-land long enough knows that printf (or java.util.Formatter) serves one main purpose: it's a poor substitute for built-in variable interpolation in the language. Unfortunatly Scala also lacks variable interpolation and there isn't much we can do about it: our BDFL has ruled. But, there is another use for printf, as a shortcut for applying special formatting for some value types.

In Java: String.format("%.2f USD at %tD", 133.7, Calendar.getInstance()); In Scala: The whole code: C style for loops in Scala with break and continue. (If you don't want to read about how I ended up hand rolling C style loops in scala then go straight to the end result here.) Becoming really rich with C# is a great example of what's coming in the version of C# in Visual Studio 2010 and it makes it obvious that C# is leaving Java in the dust.

That why I'm looking at scala. As an excercise, I translated the c# version of the stdDev function into Scala, copying the imperative non-functional style in the original c# code Imperative version of stddev Couple of notes here. I'm using the joda time scala wrapper (import org.scala_tools.time.Imports._). The sum() and average() functions should be obvious. getReturn(now - 7.days, now) returns an Option[Double] of the increase in price in the last seven days as per the c# version. I wanted to convert my stdDevImperative to a functional style, getting rid of all those icky vars. Simple Recursive version of stddev Next step: allow the compiler to use "tail call optimisation". Unfold version of stddev. A Simple Publish/Subscribe Example in Scala. Here is an example where using a simple publish/subscribe mechanism allowed me to clean up some of my early Scala code. My Mimprint program (now also on github) was originally written in Java, then ported to Scala soon after I first started learning that language.

As such, much of that original ported code was "Java written in Scala". As I have continued to internalize the Scala approach I have gone back and modified various parts of the program to make it cleaner. In one part of the program I set up a collection of menu checkboxes to allow the user to enable or disable various features. My original Java-ish Scala code to do this looked something like this (with irrelevant parts omitted): There were two things about this code that I didn't like: Mutable instance variables using var, particularly since they were not really variable.

Writing a publish/subscribe handler in Scala is pretty easy, and for me it was even simpler, as I already had one. Java <-> Scala interop: transparent List and Map conversio. Initializing Immutable Variables in Scala. One of the guidelines I picked up when I learned Scala is to use immutable variables as much as possible. Besides the trivial but satisfying detail of making the declaration of an immutable variable (val) take no more characters than a mutable one (var), Scala also provides some interesting ways to set the values into those immutable variables. In Scala, immutable variables are identified by declaring them using the val keyword rather than var.

In Java, immutable variables are identified by adding the final qualifier to the variable declaration. But a Java final variable has slightly different semantics than a Scala val: in Java, you can declare a final variable without specifying a value for it, then fill in the value later. Java allows the variable to be assigned once, after which it can not be assigned again. In Scala, a concrete val must have its value assigned as part of the definition. Consider this sample Java class, Interval, which represents an interval on the real number line.

Scala vs Clojure – Round 2: Concurrency! Commercial usage of Scala at ClariFI. Update: There's some additional comments and discussion on reddit. Also, made minor edits on our company background to reflect our recent rebranding. For a while I've been meaning to put together a post discussing my experience using Scala successfully in a large commercial product. First, a bit of background: the company I work for, Capital IQ, delivers fundamental and quantitative research and analytics software to the investment management, banking, corporate, and academic communities. Our flagship quant product, ClariFI, supports asset managers at every stage of the quantitative investment process: building and backtesting of factors, portfolio optimization, simulation of trading strategies, performance and risk attribution, overall data management (including organizing huge amounts of time series data pulled from a diverse set of raw sources), and lots more.

In addition to ClariFI, though, we have started serving up some of our analytics to the Capital IQ web application. Takeaways. Bigvisiblewall - Project Hosting on Google Code. Scala: The ‘_=’ mixed identifier. I’ve been playing around with Scala a bit and in particular following some of the code examples from Daniel Spiewak’s ‘Scala for Java Refugees’ article on Traits and Types. One thing that I got a bit confused about in one of the examples was the use of the ‘_’ at the end of one of the function definitions: From my limited understanding of the language the ‘_’ (or placeholder syntax) is often passed to functions when we only want to partially apply the function to its arguments but when you use it in that context there’s usually a space between the function name and the ‘_’ so it wasn’t being used like that.

From Programming in Scala: Remember that you need to leave a space between the function name and the underscore, because otherwise the compiler will think you are referring to a different symbol, such as for example, a method named println_, which likely does not exist. It seems quite similar to the way we would use properties in C#. Type Lists and Heterogeneously Typed Arrays. In previous blog posts (HList in Scala and HList in Scala Revisited (or Scala Metaprogramming Works!)) I described a way to encode heterogeneously typed lists, HList, in Scala. This data type can be used as a generic replacement for the TupleX types found in the Scala library. In this post I will generalize the concept of type lists and introduce a new data type, HArray. Note: the MetaScala code linked to in this post must be compiled using a recent Scala 2.8.0 build. I've given up on making it work with 2.7.x. Type Lists In HList the types of the elements and the element values are intertwined in the same type. // Abstract base type sealed trait TList // The empty type list final class TNil extends TList // A pair of a type and a type list final class TCons[H, T <: TList] extends TList { type Head = H type Tail = T } // For infix notation type ::[H, T <: TList] = TCons[H, T] which would allow us to build type lists using infix notation, for example: Heterogeneously Typed Arrays.

Scala IO Action Item 1. Some Tasty Scala Sugar. I have finally been getting around to working some more on Scala+Android. A lot needs to be done, especially since I am talking about it next month at the Silicon Valley Code Camp. Scala advocates (and I guess that includes me) often say that is very easy for application developers to use Scala, i.e. that "most" developers are never exposed to the more complex aspects of the language. The folks who "suffer" are APIs developers. I've mostly fallen into the first camp (app developers), but now that I'm trying to create a Scala API on top of the Android SDK, I get exposed to more aspects of Scala. Clearly you could follow a similar pattern in Scala. Remember that in Scala, an object is a singleton (in this case, there will be a single instance of name per instance of User). What is really cool is that you can declare methods on the object. So now you can use this like: Very nice.

So how to do this? Pretty cool, huh? Pretty obvious at this point... Here is how I coaxed that to work: Another tour of Scala. Scala Refactoring Term Project. Type Safe Builder in Scala, Part 4. Type Safe Builder in Scala, Part 3. Concurrency on the JVM Using Scala. Encoding functional dependencies in Scala. Type Safe Builder in Scala, Part 2. Side-effects with Kestrel in Scala. Research: Programming Style and Productivity. Is Scala ready for the enterprise? Clojure vs Scala, Part 2. On Scala’s future. A Tiny Review of Scala. Pragmatic Real-World Scala. Kiama - Google Code. Scala is my next choice.