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

Why Scala? Before answering the question of "Why Scala?", we first need to answer the question "what is Scala?" From the Scala website, the following overview can be found: Scala is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. For some developers, these incentives will be enough to lure you away from Java into the Scala world. So, once again, "why Scala?" In a post titled "Scala: The best of both Ruby and Java", Ian describes that it might not be a choice between Java and Scala, but instead the choice to use a combination of Java and Scala as an alternative to other language choices such as Ruby: Many programmers love Ruby, they just can’t get enough of it. To further show the reduction of code in a less trival example, Ted Neward explores the differences between a class developed in Java, C#, Visual Basic, Ruby and Scala in his blog posting Scala pt 2: Brevity. Continuing on, Ian notes that:

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 The Scala Programming Language Scala as the long term replacement for java/javac? Don't get me wrong - I've written tons of Java over the last decade or so & think its been a great evolutionary step from C++ and Smalltalk (lots of other languages have helped too like JavaScript, Ruby, Groovy, Python etc). However I've long wanted a long term replacement to javac. I even created a language to scratch this itch. Java is a surprisingly complex language (the spec is 600 pages and does anyone really grok generics in Java?), with its autoboxing (and lovely NPE's hiding in there), primitive types, icky arrays which are not collections & general lack of polymorphism across strings/text/buffers/collections/arrays along with extremely verbose syntax for working with any kind of data structure & bean properties and still no closures (even in JDK7) which leads to tons of icky try/catch/finally crapola unless you use frameworks with new custom APIs & yet more complexity. So whats gonna be the long term replacement for javac? So why Scala? e.g. in Java List<String><String> in Scala

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 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. The easiest way to get started with Scala is by using the Scala interpreter, which is an interactive “shell” for writing Scala expressions and programs. scala> 1 + 2

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

Can Your Programming Language Do This? by Joel Spolsky Tuesday, August 01, 2006 One day, you're browsing through your code, and you notice two big blocks that look almost exactly the same. // A trivial example: alert("I'd like some Spaghetti!") These examples happen to be in JavaScript, but even if you don't know JavaScript, you should be able to follow along. The repeated code looks wrong, of course, so you create a function: function SwedishChef( food ) { alert("I'd like some " + food + "!") OK, it's a trivial example, but you can imagine a more substantial example. Now you notice two other blocks of code which look almost the same, except that one of them keeps calling this function called BoomBoom and the other one keeps calling this function called PutInPot. alert("get the lobster"); PutInPot("lobster"); PutInPot("water"); alert("get the chicken"); BoomBoom("chicken"); BoomBoom("coconut"); Now you need a way to pass an argument to the function which itself is a function. Look! Can your language do this? Jeez, that is handy.

Scala Syntax Primer Scala runs on the JVM and can directly call and be called from Java, but source compatibility was not a goal. Scala has a lot of capabilities not in Java, and to help those new features work more nicely, there are a number of differences between Java and Scala syntax that can make reading Scala code a bit of a challenge for Java programmers when first encountering Scala. This primer attempts to explain those differences. This primer is not intended to be a complete tutorial on Scala, rather it is more of a syntax reference. Most of these syntax differences can be explained by two of Scala's major goals: Minimize verbosity. (0/:list)(_+_) Scala is an integrated object/functional language. You can run the Scala interpreter and type in these examples to get a better feel for how these rules work. Contents Basics Scala classes do not need to go into files that match the class name, as they do in Java. Keywords Symbols and Literals Expressions Case and Patterns For Expressions Arrays Tuples Classes

A Taste of 2.8: The Interactive Interpreter (REPL) The Scala Interpreter (often called a REPL for Read-Evaluate-Print Loop) sits in an unusual design space - an interactive interpreter for a statically typed language straddles two worlds which historically have been distinct. In version 2.8 the REPL further exploits the unique possibilities. Package and Class Completion On startup, the REPL analyzes your classpath and creates a database of every visible package and path. scala><tab> collection compat concurrent scala> org.w3c.dom.DOMI<tab> DOMImplementation DOMImplementationList DOMImplementationSourcescala> org.w3c.dom.DOMImplementation Member Completion Both static and instance methods of objects are also available. scala> val x = "abc" x: java.lang.String = abc scala><tab> regionMatches replace replaceAll replaceFirst scala> java.lang.String.c<tab> scala> java.lang.String.copyValueOf And because this is all accomplished on the fly via reflection, even anonymous classes you've only just defined are equally accessible.

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

Excellent Overview of Functional Programming 14 Feb 2008 I just ran into an article on DZone that totally threw me off my chair in terms of content. It’s titled (ambitiously enough) “Functional Programming For the Rest of Us“. Basically the article attempts to explain many of the common FP techniques in terms that imperative programmers can understand. More importantly, it motivates these explanations with a long and rambling set of real-world reasons. It’s worth noting that the author claims to be presenting his explanations in Java, but is in fact devising an extension of Java to represent FP constructs more concisely. The really interesting bit is how the author motivates FP through a combination of real-world examples and lengthy reasoning. So grab yourself a cup of coffee and a box of donuts (it’ll take you about that long to finish the article), and slog your way through.

Related:  comparison