background preloader

Scala 3

Facebook Twitter

Scala Lifting Off ? Scala as the Replacement to the Java Compiler? 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.

Java even has type inference, it just refuses to use it to let us save any typing/reading. So why Scala? A case study in Scala API design. Josh Cough had an amusing article on pimping vs fixing libraries. He ran into an intolerable method in the Java standard libraries and decided to fix it with the Pimp My Library pattern. Today I want to pimp a different Java library: Lock. Scala has higher-level ways of dealing with concurrency than Locks, but every now and then you need to get down with the nitty-gritty and do some manual locking.

By Java standards, Lock is a pretty good library, but I wanted to see if Scala could do better. Basic Locks Here's what the Lock interface looks like in Java: interface Lock { void lock(); void lockInterruptibly(); Condition newCondition(); boolean tryLock(); boolean tryLock(long time, TimeUnit unit); void unlock(); } As a first approximation, let's distill the basic features (lock, unlock) into a Scala trait: Lock was introduced as a better alternative to Java's synchronized keyword, but in the simple case it's actually worse. Compare this to using synchronized directly in Java: Advanced Locks. The TAPIR book. 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.

Java even has type inference, it just refuses to use it to let us save any typing/reading. So why Scala? Électricité de France - Alex McGuire | The Scala Programming Lan. Alex McGuire talks about his experiences at Électricité de France Trading (EDFT) as Team Leader for the group developing applications for energy derivatives trading and pricing. He explains the benefits EDFT has gained by replacing a substantial part of their 300,000 lines of Java code with Scala. Alex, a mathematician and former options trader, has over 15 years of development experience creating financial trading applications. Why did EDFT start using Scala? Alex: Perhaps I need to tell you a little of what EDFT does so you can understand the context. In the past EDF produced power to meet their consumers demand. The problem was essentially one of forecasting demand and making sure you had enough capacity on line to meet it. The trader group at EDFT take the real assets like coal or oil based power stations, gas storage units, hydro electric dams, emissions contracts, just about everything related to energy, and try to model them as financial products rather than as physical things.

Matrices 5. Loggingtools in Scala. Import <span class="skimlinks-unlinked">org.slf4j. {Logger</span>, LoggerFactory} trait Log { private val log = LoggerFactory.getLogger(getClass) def trace(message:String, values:Any*) = <span class="skimlinks-unlinked">log.trace(message</span>, <span class="skimlinks-unlinked">values.map(_.asInstanceOf</span>[Object]).toArray) def trace(message:String, error:Throwable) = <span class="skimlinks-unlinked">log.trace(message</span>, error) def trace(message:String, error:Throwable, values:Any*) = <span class="skimlinks-unlinked">log.trace(message</span>, error, <span class="skimlinks-unlinked">values.map(_.asInstanceOf</span>[Object]).toArray) def debug(message:String, values:Any*) = <span class="skimlinks-unlinked">log.debug(message</span>, <span class="skimlinks-unlinked">values.map(_.asInstanceOf</span>[Object]).toArray) def debug(message:String, error:Throwable) = <span class="skimlinks-unlinked">log.debug(message</span>, error) def debug(message:String, error:Throwable, values:Any*) =

Pimp vs Just Plain Fix my Library. I assume most people familiar with Scala are familiar with Pimp My Library. It's just a fun and useful thing to be able to add a missing method onto an API, or to sometimes be able to treat an object like something else. As fun as it is (especially with the word Pimp), I kind of want to take the fun out of it a little bit. I want to say that its not just about adding that one great feature. Let me make this boring and annoying assertion: Pimping is most useful for fixing crappy, terrible, miserable API.

And while that's cool, and useful, it kind of sucks. There's so much terrible code out there that is a nightmare to work with. Now for an example. Enumerate public int enumerate(Thread[] list) Copies into the specified array every active thread in this thread group and its subgroups. First, the checkAccess method of this thread group is called with no arguments; this may result in a security exception. Parameters: list - an array into which to place the list of threads. Returns: WHAT?!? Deconstruct(or)ing Scala. The question of whether to use a constructor or a factory method for object construction is not new; we've had this discussion for years in the Java community. Scala's approach to object construction has a few features that will undoubtedly reignite this debate. On the one hand, ordinary object construction is significantly more powerful than in Java - first, the all the ordinary Java boilerplate of assigning constructor parameters to member variables is abolished.

What in Java would look like this: becomes the concise and sensible More significantly, Scala's trait mechanism allows for extension of a class definition at the use site; for example, if I have a trait that adds rendering logic to a class, I can mix it in only when I need it. So Scala's constructors are really powerful and you really want to use them, right? It turns out that there are some subtle issues that arise if you start adding more logic to constructors in Scala. Let's look at something a little more complex. Interview: Miles Sabin, Scala Eclipse IDE Developer | The Scala. Miles Sabin Miles Sabin runs a Scala-centric consulting company, Chuusai Ltd, but is perhaps best known in the Scala world for his outstanding contribution to the Scala IDE for Eclipse. Miles has made a business out of providing companies using Scala with the tools, practical advice, development help, training and the general support they need to be successful quickly.

He took time out to talk about his early Scala experiences, the type of work he now does and some inside scoop on where the Scala IDE for Eclipse is going. How did you get interested in Scala? Miles: Well it wasn't really Scala that first caught my eye. My intuition was that language-level support was the way to go, and set out on a long term project to find or invent something appropriate. Although very different from Funnel, I took one look at Scala and it was love at first sight. What was it like to learn Scala? Miles: Programming languages are a passion of mine, so learning Scala was joy. What did you do to the IDE? Equality &amp; Scala. I'm just through reading three different sources on equality in less than a week. They all said pretty much the same thing, with a minor variation here or there.

It got me thinking about it, and I have some thoughts to share. For this discussion, I'll assume you are familiar with how to do equality correctly. My examples follow the model given in this article. Let's start with two simple classes: 1.class Point (val x : Int, val y : Int) { 2. override def toString = "(%d, %d)" format (x, y) 5.class Point3D (x : Int, y : Int, val z : Int) extends Point(x,y) { 6. override def toString = "(%d, %d, %d)" format (x, y, z) Now, a proper equality method in these classes would look like the following: 01.class Point (val x : Int, val y : Int) { 02. override def toString = "(%d, %d)" format (x, y) 03. override def hashCode = 41 * (41 + x) + y 04. override def equals(other : Any) : Boolean = other match { 05. case that : Point => ( 06. that.canEqual(this) 07.

&& this.x == that.x 08. && this.y == that.y 31. 35. Scala MultithreadedTC Port. I haven't posted in quite a while now, but only because I've been working really hard. I asked Doug Lea if I could help him on his upcoming Scala concurrent data structures endeavor, especially on testing and to my surprise he sounded quite happy about the idea. He's going to get started sometime in July, and I figured from now until then would be a great time to get caught up on testing concurrent data structures, and have a nice framework in place before any code actually gets written. To that end, I've decided to port MultithreadedTC to Scala. The reasons for doing so are quite simple - we can take advantage of Scala's flexible syntax, HOF's, yada yada...I don't think that that needs to be explained yet again.

And, I don't think this particular example demonstrates something like, "but here those features are particularly valuable". The resulting code is definitely nicer than the original Java code, and that's simply all. This code tests the interactions of two threads. Sort of... Why ARM is not quite enough. Scala, Clojure - stick to Python? : programming. Scalable Algorithms 2. , I told of a programming challenge taken, and my first go at it.

While the algorithm I came up with had a certain cleverness, there was much to criticize about it. Another friend, who had received the same challenge, attacked the problem from a different perspective. His algorithm was not as liberal with the input as mine, as it accepted only abbreviations or single words. It would match a prefix of a word other than the first one, though, which is something mine didn't. For instance, if there was an option "create application shortcuts", it would match that against "cas" or any prefix of it (eg. "ca"), "create" or any prefix of it, "application" or any prefix of it and "shortcuts" or any prefix of it. Map of Prefixes I won't post his algorithm of it here (though I'd be happy to link to a post of his, if he does so), but the idea was precomputing a couple of maps: one of full abbreviations into set of menu options, and one of words into set of menu options. 01.val wordsep = "[ :,;]" 15.

Scalable Algorithms 3. Back to matching shortcuts to menu options, I decided my best option would be a deterministic finite automaton. It would make excellent use of partial input, and take much less space than a set of all possible inputs accepted -- to make use of state machine lingo -- by each menu option. Now, anyone who has ever worked with DFA before will tell you that the trick to build one is to first generate the regular expression which represents what you want to match.

Yes, that's your good, old RegExp. Well, not fully... you can't have back references, for one thing. But most of what you think of as regexp will do. So, what regular expression would match our input? Let's take a small menu option: "New Tab". So, let's get the first word, and see how far we can take. Naturally, each word would follow the same pattern, but what about the whole menu option?

In fact, we can do it using foldRight. But... we can match regular expressions to strings just as well as DFA. 01.val wordsep = "\\W+" 08. 08. Parser Surprise. David Vydra found it surprising that he couldn't do the following: 1.scala> -1.toString 2. <console>:1: error: ';' expected but '.' found. 3.-1.toString 5. I was surprised too by some similar example, from page 208 of Programming in Scala: A Comprehensive Step-by-step Guide Given that example, I would not expect that message in particular, but I would expect an error: that "unary_-" is not a member of java.lang.String, like this: 1.scala> -(1 toString) 2. 3.-(1 toString) Or, in fact, like this: 1.scala> +1.toString 2. 3.+1.toString Some people have raised the question of operator precedence, claiming "-" ought to have more precedence than ".

". So let's take a look at Scala's operator precedence rule. (all letters) | ^ & < > = ! The exception is that an assignment has lower precedence than any other operator. These, though, are the precedence rules for infix operators, and "-" in "-1" is not infix, but prefix. 01.scala> class X { 02.| def unary_- = {println("Unary -"); this} 07.defined class X 16.Unary - Scalable Algorithms. It's common knowledge that the best way of learning a new language is writing a program you wanted in it.

Or, perhaps I should say, that's the quickest way of learning a language -- you should beware of the gaps in knowledge of the language that can result from this approach. Well, I was trying to do that with Scala, but I always stopped because there was something more I wanted to learn before continuing with one project or other. It was then that a friend posed a challenge, and that finally broke the programmer's block I was having. He has written a small program -- in Scala -- with few but loyal followers to help in his gaming sessions, and he wanted something to help with fast keyboard selection. His idea was having an algorithm that would search available menu options based on a few input characters, which would typically stand for an abbreviation of that menu. Preferably, order the result too using some kind of heuristics. Well, I wound up writing many solutions to the problem. 25. Scala&#039;s Projections. While reading a cool posting by Chris Smith regarding F#, I noticed something he did not remark on, which is very common in functional programming languages.

In his code, he makes a sequence from 3 to 3,628,800, and then does a lot of stuff on it. He transforms everything into strings, computes stuff from that string, etc. Here's a Scala equivalent: 01.object Factorial { 02. private [Factorial] class Fact(n : Int) { 03. def ! 05. implicit def toFact(n : Int) : Fact = new Fact(n) 08.import Factorial 10.println((3 to (10!)) 11. map (n => (n, (n.toString 12. map (_ asDigit) 13. map (_ !) 14. reduceLeft (_+_)))) 15. map (p => (p._1, p._1 == p._2)) 16. filter (_._2) 17. map (_._1) 18. reduceLeft (_+_) Go ahead, open an interpreter and try it. Depending on your Java memory settings, you'll get an Out of Memory error. This magic happens because those map and filter functions are non-strict. As it happens, you are probably familiar with this concept at another level. 1.val ex1 = 2 + 3 2.def ex2 = { 2 + 3 } Scala Improvement Documents Library | The Scala Programming Lang. Pragmatic Real-World Scala (short version) The Price of Abstraction.

Scala really is a &quot;better Java&quot; Enhancing the Scitter library. Good Use Case for Named Arguments. Simple Scala Keyword Parameters. CK: Scala function objects from a Java perspective. Bending a language to your will. Eight Scala or Scala related talks in the coming JavaOne. Programming Scala. The Smileys in Scala. A problem of language. Scala over Ruby - My Debate Ends.

Scala and XML - Part 1. The Goals of Scala&#039;s Design. Pour some sugar on HttpClient. Beware of Scala’s type inference ! Scala cheatsheet. Code:xml-pattern-matching [Scala Wiki] 3 Scala gotchas. How Scala Changed My Programming Style. Scala multiple assignment. Embedding the Scala Interpreter. Scala 2.8 Preview.