background preloader

Roundup: Scala for Java Refugees

Roundup: Scala for Java Refugees
13 Feb 2008 To be honest, I’m somewhat kicking myself for writing this post. As I’ve said many times: roundup posts are for people who are too lazy to write real content. I can’t tell you how many blogs I’ve come across which have a roundup-to-post ratio of easily 3:1. Meta-roundups aside, I decided (after much deliberation) that a single post linking to all six parts of the series would be useful to one or two people. Of course it’s always possible that you subscribe to my way of looking at things. Part 1: main(String[]) Introductory article giving motivation for learning Scala and some first steps to “get your feet wet” in the language. Part 2: Basic OOP Looking at Scala’s syntax in a little more detail. Part 3: Methods and Statics Scala’s method syntax is far too powerful to cover in a single post. Part 4: Pattern Matching and Exceptions Pattern matching is one of the most useful constructs in the entire language. Part 5: Traits and Types Part 6: Getting Over Java Related:  Scala

Effective Scala Table of Contents Other languages 日本語Русский简体中文 Introduction Scala is one of the main application programming languages used at Twitter. Scala provides many tools that enable succinct expression. Above all, program in Scala. This is not an introduction to Scala; we assume the reader is familiar with the language. This is a living document that will change to reflect our current “best practices,” but its core ideas are unlikely to change: Always favor readability; write generic code but not at the expensive of clarity; take advantage of simple language features that afford great power but avoid the esoteric ones (especially in the type system). And have fun. Formatting The specifics of code formatting — so long as they are practical — are of little consequence. This is of particular importance to Scala, as its grammar has a high degree of overlap. We adhere to the Scala style guide plus the following rules. Whitespace Indent by two spaces. Naming Use short names for small scopes Use vals Prefer:

mapreduce - Scala analogues of QtConcurrent Scala Documentation Manifests: Reified Types Reification (n.): When an abstract concept [...] is treated as a concrete 'thing'.[1] When Java-the-language added generic types in version 1.5, Java-the-virtual-machine (JVM) did not. Generic types are a fiction of the compiler. By contrast, when C# added generic types in version 2.0, the .NET Common Language Runtime (CLR) added them as well. Java's type erasure leads to some peculiar limitations. Starting with version 2.7.2, Scala has added manifests, an undocumented (and still experimental) feature for reifying types. To use Manifests, simply add an implicit scala.reflect.Manifest[T] parameter to your method, like so: def name[T](implicit m: scala.reflect.Manifest[T]) = m.toString This method prints the name of any Scala type. name[Int => Int]// returns "scala.Function1[int, int]" When using implicit parameters, you usually have to declare a implicit identifier with the same type as your method expects, in the same scope where the method is called. Appendix: Other Methods on Manifests

typesafehub/sbteclipse Comparing Apples to Pears in Scala - or Abstract Types to the Rescue Abstract types in Scala can make your life much easier. In this blog I’m going to recap my intellectual journey to compare 'apples to pears' in a typesafe manner, which led me to abstract types. My quest was to write code, which enables me to compare different kinds of currencies as elegant as possible. What I wanted was a very simple DSL with which I could do the following: The very beginning That’s where I started out: You probably see already which problem we’ll encounter. So my question was how to cope with this situation. No real option for the problem One second I considered to add the following check to the Money’s compare method: Needless to say that this cannot be considered a viable solution. Abstract types to the rescue Minutes later I remembered abstract types, which provided the solution I was exactly looking for. Next I can define an OrderedMoney trait in order to introduce the Ordered trait, for which the compare method is needed in the first place. Finishing touch All at once

» Quick starting Scalatra or In which I discover Scalatra and sbt Everything's Beta Over the weekend, I was researching various frameworks for implementing a REST API. Although I had already started the implementation using Tornado, I wanted to see what else was out there. And am I glad I looked. I discovered Scalatra which seems to be exactly what I was looking for; a lightweight, sinatra-esque way to map URLs to actions that easily lends itself to testing. Who wouldn’t want to write tests like this? // taken from MyScalatraServletTests extends FunSuite with ShouldMatchers with ScalatraTests { // `MyScalatraServlet` is your app which extends ScalatraServlet route(classOf[MyScalatraServlet], "/*") test("simple get") { get("/path/to/something") { status should equal (200) body should include ("hi!") I cloned the repo, ran the examples and decided my search had ended. However, while running the example was easy enough, I wasn’t sure of how to get started with an actual app. Pre-reqs: Install java, I have java 1.6. Great!

Scala’s parallel collections Scala 2.9 introduced parallel collections, which mirror most of the existing collections with a parallel version. Collections that have been parallelized this way have received a new method called par which magically parallelize certain operations on this collection. For example, here is a sequential version: And the parallel version (notice the extra par keyword): Obviously, the ordering will change each time you run the parallel version. This piqued my curiosity and I decided to dig a bit further, starting with investigating what exactly is happening behind the scenes. First of all, the parallel collections are based on an article called “A Generic Parallel Collection Framework”, by Martin Odersky, Aleksander Prokopec et al, which I highly recommend. Sadly, this article ended up being the only highlight of my research in this area, because the more I dug into the Scala parallel collections, the more disappointed I became. Lack of control Silver bullet illusion Here is a quick example: Bloat

How to compile and run scala code quickly in vim Yes, Virginia, Scala is hard - Good Stuff Let me first say that I am a Scala lover and have been a Scala champion for almost 5 years. I've written books and articles on Scala. I've worked with dozens of companies that have launched Scala and Lift projects. I've code reviewed many dozens of Scala projects. I used to think that Scala was easy. So, why is Scala hard? Scala tries to be too many things. But if you've got a team that's closer to the mean skill-wise, Scala may not be a win for your company (this depends on management... does it want to use the challenge of Scala as a way of filtering and improving the team?) So, how can you figure out if Scala will be "easy" or "hard" for your organization: A couple of notes: Yes, Scala's type system is powerful and leads to some beautifully functioning code like Scala's collections.

S-99: Ninety-Nine Scala Problems These are an adaptation of the Ninety-Nine Prolog Problems written by Werner Hett at the Berne University of Applied Sciences in Berne, Switzerland. I (Phil Gold) have altered them to be more amenable to programming in Scala. Feedback is appreciated, particularly on anything marked TODO. The problems have different levels of difficulty. Your goal should be to find the most elegant solution of the given problems. Solutions are available by clicking on the link at the beginning of the problem description. [I don't have example solutions to all of the problems yet. Working with lists In Scala, lists are objects of type List[A], where A can be any type. The solutions to the problems in this section will be in objects named after the problems (P01, P02, etc.). In many cases, there's more than one reasonable approach. P01 (*) Find the last element of a list. Example: scala> last(List(1, 1, 2, 3, 5, 8)) res0: Int = 8 P02 (*) Find the last but one element of a list. P05 (*) Reverse a list. Examples:

Is Scala really too complex for average developers? I have been evaluating Scala for quite some time now as an alternative to Java for enterprise development and one of the most common criticisms I have seen against Scala is that it is too complex for average developers. A quick Google search on Scala Complexity returns numerous links to blogs both defending and criticizing Scala for its perceived complexity. In my opinion one key aspect that has been ignored in this debate is that adoption of a framework/language/whatever in a large enterprise is almost never about technology per say, but has more to do with the culture of the organization. To better understand the statement ‘Scala is too complex for average developers’, we will have to dig a little bit deeper into the prevalent culture in most IT departments in large enterprise today. Type X programmers could be described as: Individuals who lack ambition, dislike responsibility and prefer to be led. Type Y programmers could be described as: Is Scala too complex for Type X programmers?

Real-World Scala: Dependency Injection (DI) ← Posted: 2008-10-06 In this second post in the Real-World Scala series I am going to discuss how to implement/achieve Depenency Injection (DI) in Scala. Scala is a very rich and deep language that gives you several ways of doing DI solely based on language constructs, but nothing prevents you from using existing Java DI frameworks, if that is preferred. Using the Cake Pattern The current strategy we are using is based on the so-called Cake Pattern. Note: I will try to explain things in steps which I refactor towards the final version (this is only to help with the understanding), so please wait with yelling: “This sucks!” First, let’s create a UserRepository (DAO) implementation. Here we could have split up the implementation in a trait interface and its implementation, but in order to keep things simple I didn’t see the need. Now let’s create a user service (also a dummy one, merely redirecting to our repository). Here you can see that we are referencing an instance of the UserRepository.

What features of Java have been dropped in Scala? Despite more complex and less intuitive syntax compared to Java, Scala actually drops several features of Java, sometimes for good, other times providing replacements on the standard library level. As you will see soon, Scala isn’t a superset of Java (like Groovy) and actually removes a lot of noise. Below is a catalogue of the missing features. break and continue in loops Every time I see code like this: I feel as if it has been written by a guy who truly misses the times when goto wasn’t yet considered harmful. Getting rid of break requires a little more though, but generally extracting a loop to a separate method/function (or at least putting it at the end of existing method) and using return instead will do the trick. break and continue – we thank you in the name of our fathers and grandfathers for your contribution to imperative programming. Arrays And don’t worry, behind the scenes Scala compiler will use the same efficient array bytecode as if you were using plain arrays in Java.