Thursday, April 28, 2011

JQuery each issues

Good demonstration that jQuery's each then $() pattern is not only ugly, but slow too

http://jsperf.com/jquery-each-vs-quickeach

Real world functional programming at Twitter

Scaling Scala at Twitter by Marius Eriksen. It was interesting and there are objects too.

Scala Tips

"Add explicit return types to all implicits."

"Scala’s not Ruby. Scala’s not Haskell. Borrowing inspiration is good, but don’t force Scala into something it’s not."

"Prefer vals to vars. (But remember not all vars are created evil.)"

"Avoid implicit conversions that “massage” types. Prefer explicit conversions."

"Avoid case class inheritance."

"Beware initialization issues. Remember that class/trait/object bodies are constructors. (Avoid the Application trait.)"

Programming in Scala 1st edition released

Programming in Scala 1st edition released as free online resource.

Saturday, April 23, 2011

jQuery Mobile 1.0 Alpha 4.1 Released!

jQuery Mobile: Touch-Optimized Web Framework for Smartphones & Tablets

A unified user interface system across all popular mobile device platforms, built on the rock-solid jQuery and jQuery UI foundation. Its lightweight code is built with progressive enhancement, and has a flexible, easily themeable design. Alpha 4.1 Release Notes

Oracle's NetBeans 7.0 - Support for the JDK7 Developer Preview and HTML5

Oracle released NetBeans version 7.0, It becomes the first open source IDE to support JDK 7, providing both syntax support for the new language features, and code inspectors to help update existing code bases to take advantage of the new capabilities of the JDK platform. The specific JDK 7 features are:
  1. Strings in switch
  2. Diamond operator (new LinkedList<>())
  3. java.util.Objects
  4. JSR 292 (Exotic identifiers)
  5. New integer literals
  6. Multicatch
  7. Automatic resource management
Given that JDK 7 is not yet released, the NetBeans team will continue to track its progress closely. Oracle's Senior Director of Product Management, Duncan Mills, told InfoQ that a point release is planned to accommodate any changes.

With a high proportion of NetBeans users developing Swing applications (around 50% of NetBeans users are building JavaSE applications, according to Mills), the visual editor tools for Swing continue to receive attention. NetBeans 7 adds a new visual editor, GridBag Customizer, to the tool. Elsewhere, Oracle have also added support for Maven 3 and Git 1.7, integrated JUnit 4.8.2, and added remote HTTP URL support for Javadoc in libraries and Java platforms, providing support for “remotely hosted” Javadoc.

Java EE developers will find better support for Contexts and Dependency Injection (CDI) with a new editor's hint for creating qualifiers and a CDI specific inspector for observers/producers/injectables. There are also some improvements to support for the Java Persistence API, new support for Bean Validation, and the JSF PrimeFaces component library has been incorporated.

In terms of application server support, NetBeans 7.0 includes better integration with Oracle WebLogic 11g with both faster deployment times, and a new server runtime node displaying deployed features and applications. GlassFish integration has been updated, so that NetBeans now supports GlassFish 3.1, and includes new support for management of remote instances and deployed applications. Support for Tomcat 7 and the upcoming JBoss 6 are also included.
For web developers the HTML editor includes support for syntax checking, code highlighting and autocompletion for HTML5, with support for CSS3 planned for a future release. NetBeans' popular PHP support, used by around 220,000 developers according to Mills, has also seen some improvements with new support for Generate phpDoc, and new rename and safe delete refactorings.

As we previously reported NetBeans 7 no longer supports Ruby/RoR.
Although the open-source Java IDE market is dominated by Eclipse, NetBeans continues to grow. Mills told us that the product has around 880,000 "Active Users" (i.e. users who allow the product to "phone home" periodically), and sees about 550,000 downloads a month. The target is to grow that to around 1 million. The beta has aprox. 40,000 downloads between Nov 2010 and today.

For more information click here

Google's Guice - Annotation-Driven Dependency Injection

Guice 3.0 has been released last month,it alleviates the need for factories and the use of new in your Java code. Think of Guice's @Inject as the new new. You will still need to write factories in some cases, but your code will not depend directly on them. Your code will be easier to change, unit test and reuse in other contexts.

Guice embraces Java's type safe nature, especially when it comes to features introduced in Java 5 such as generics and annotations. You might think of Guice as filling in missing features for core Java. Ideally, the language itself would provide most of the same features, but until such a language comes along, we have Guice.

Guice helps you design better APIs, and the Guice API itself sets a good example. Guice is not a kitchen sink. We justify each feature with at least three use cases. When in doubt, we leave it out. We build general functionality which enables you to extend Guice rather than adding every feature to the core framework.

Guice aims to make development and debugging easier and faster, not harder and slower. In that vein, Guice steers clear of surprises and magic. You should be able to understand code with or without tools, though tools can make things even easier. When errors do occur, Guice goes the extra mile to generate helpful messages.

For an introduction to Guice and a comparison to new and the factory pattern, see Bob Lee's video presentation. After that, check out our user's guide.
We've been running Guice in mission critical applications since 2006, and now you can, too.

New in 3.0

In InfoQ article, The most notable change to Guice 3.0 is the inclusion of a fully compliant JSR 330 injector. (JSR 330 was finalized in 2009.) In fact, “Guice 3.0 is the reference implementation for JSR 330,” according to Dhanji Prasanna of the Guice development team.

Because there is still a need to write factory code, Guice 3.0 adds assisted injection, which automatically generates factory implementations, alleviating the need to write boilerplate code. There are also new Binder methods and enhancements to injections that allow you to return bindings based either by type, scope, existing bindings or all. The framework also extends the SPI for elements to expose elements introduced by third-party extensions. Additional enhancements include improved OSGi support, numerous servlet extensions, support for singletons, and Struts 2 integration. Other features include:
* Simpler stack traces when AOP is involved
* Duplicate bindings are ignored rather than throwing an exception.
* Repackaged cglib, asm & guava classes are now hidden from IDE auto-imports
* Support for Maven

Guice vs. Spring

As is often mentioned in discussion groups the Spring framework already supports dependency injection. The most often voiced concern is that developers must choose between Guice and Spring. While Guice offers an alternative to Spring’s DI methods, it does not supplant the Spring framework. The truth is that Guice can coexist with Spring, and can be used independently or in conjunction with Spring. For example, Guice supports AOP method interceptors, allowing developers to use Spring’s transaction interceptor. There is also a SpringIntegration() class that makes it possible to bind to Spring beans. What Guice brings to the table is type safety, exception handling, and simplicity by removing both an abstraction layer and the need for XML configuration.

Finally it’s worth noting that "Guice 4.1" was just announced. The announcement is more of a footnote because 4.1 is a stripped-down "MiniGuice," suitable for very small applications. As Guice team member Sam Berlin puts it, "Guice 4.1 is a radical rethinking of Guice, dependency injection, and how java libraries are shipped." Guice 4.1 consists of a single file and can be called from this simple API:
myApp program = MiniGuice.inject(myApp.class, new Module1(), new Module2());*
 

The Guice 4.1 source file can be found at Google Code.
 

GitHub - 2m Repositories

GitHub has been announced they had passed two million git repositories hosted, In that 1.1 million code repositories and 0.9 million gist repositories.

Gists are GitHub's way of pasting small segments of code at gist.github.com, similar to Pastebin and others that allow you to take code and paste it to the web. Each gist is its own git repository, complete with version control – and as such, gists can be pulled, updated, commented upon and patches provided.

The number of code repositories includes clones (aka 'forks') of the original, so the number of unique git repositories will be somewhat smaller. However, the statistics of the repositories are interesting; over 70% have been created with the last year – with over 4500 new GitHub projects per day.

As for the breakdown of languages; 225k are Ruby-based; 138k are Javascript based 77k are Python based and 560k are classified as 'other language' projects. There is a breakdown by language on the languages stats page, but this counts the number of lines of code rather than number of projects.

Recently, tighter GitHub integration into Eclipse was released as part of Eclipse's mirroring on GitHub and Eclipse Mylyn and GitHub integration. It's now possible to hook up Mylyn to read issues from GitHub Issues 2.0, and of course sync repositories via EGit. It's even possible to create GitHub Gists via Eclipse as a way of sharing code.

Monday, April 18, 2011

PostgreSQL - Create a user, a database and grant accesses

These steps will let you create a user, a database (DB) and grant full access to the user to this DB.

All the commands are executed as the "postgres" privileged user.

For this, you use the command createuser which is provides with the postgreSQL package.
postgres@hostname:~$ createuser
Enter name of role to add: user
Shall the new role be a superuser? (y/n) n
Shall the new role be allowed to create databases? (y/n) n
Shall the new role be allowed to create more new roles? (y/n) n
CREATE ROLE
postgres@hostname:~$

Create the DB

postgres@hostname:~$ createdb testdb
CREATE DATABASE
postgres@hostname:~$

Grand access for the user to the DB

postgres@hostname:~$ psql
postgres=# alter user user with encrypted password 'password';
ALTER ROLE
postgres=# grant all privileges on database testdb to user;
GRANT
postgres@hostname:~$ 
Hope it may work for you. If you have any issues please let me know.

Saturday, April 16, 2011

Programming in Scala, First Edition

Programming in Scala First Edition released as free online resource. The HTML looks great!  

Checkout here

Tuesday, April 12, 2011

Facebook apps in Python using App Engine

Most guys used PHP for all the facebook applications. We can use Python to develop a facebook app.

There is already a sample application in facebook that uses Python and most interestingly Google app engine! The application is named 'Run With Friends'. Though I have seen this page before but never looked at it closely. So, I think this page is the right place to get started creating facebook app in Python and GAE: https://developers.facebook.com/docs/samples/canvas/.

Guardian.co.uk Switching from Java to Scala

The team behind guardian.co.uk which, according to its editor, has the second highest readership of any on-line news site after the New York Times, is gradually switching from Java to Scala, starting with the Content API, which provides a mechanism for selecting and collecting Guardian content.

The guardian.co.uk website comprises about 100,000 lines of code. It uses a fairly typical open-source Java stack of Spring, Apache Velocity and Hibernate with Oracle providing the database. Like the website, the Content API was initially being developed in Java, but the team decided to switch to another JVM-based language, Scala, in its place. Web Platform Development Team Lead Graham Tackley told InfoQ

We've been a primarily Java development shop for a number of years now, and this has largely served us well. However, as a news website we want to be able to respond to events very quickly. The core Java platform that delivers www.guardian.co.uk has a full release every two weeks. Compared with many enterprise Java applications, this is excellent. Compared with other websites, it's very poor.
So we've been looking for a while at tools, approaches and languages that enable us to deliver functionality faster. This includes using lighter weight Java frameworks like Google Guice, radically different approaches to Java development like the Play framework, and using other platforms such as Python with Django. As part of this exercise we'd been playing with Scala for a while, but unlike the others we hadn't yet used it for any production code.
We were very keen that the first non-beta release of the Content API (API, Open Platform) should be the first iteration of an ongoing evolving API, which could quickly evolve as we discovered all the interesting use cases that we hadn't initially thought of. To do this safely without breaking API clients, we needed a comprehensive set of integration tests. After some experimentation of writing these in Java, we decided instead to write just the integration tests in Scala, for three main reasons:
  1. The flexibility of the testing DSL provided by ScalaTest.
  2. We wanted to be excited about writing the integration tests, rather than them being a chore.
  3. Using Scala just for the tests meant we got to use it in anger without impacting production code directly.
After about four weeks of writing just the tests in Scala, we got fed up of having to write the main code in Java, and decided to convert the whole lot to Scala.

In general terms, how did you go about the migration? Did you re-write all the Java code in Scala for instance, or did you combine the two for a while?

The beta version of the Content API was based on a proprietary search engine. The current API uses the excellent Apache Solr (a talk on guardian.co.uk's use of Solr can be found here), and is also quite different in style to the beta one - the beta did a great job of showing us what we didn't want the API to look like. Therefore, before Scala came into the picture, we'd decided to re-implement the API rather than reuse the beta codebase. We'd spent around six weeks with three people implementing in Java before we introduced Scala, so there wasn't a massive codebase to migrate. However, we weren't prepared to stop the project for a couple of weeks while we converted to Scala, so we migrated the existing integration tests gradually. As we'd used Maven as a build tool, introducing Scala was a matter of following the instructions to use the maven-scala-plugin to build mixed Java/Scala projects. This allows Java and Scala code to co-exist in the same project, and bi-directionally depend on each other. So we could convert on a class-by-class basis from Java to Scala, which worked far better than we ever imagined: it really did just work.
We took the same approach when converting the main code: over a number of weeks, as we touched a bit of code, we converted it. We then had a couple of days mop up at the end.
What are the libraries/frameworks that you have used for development?
Since we were using a language new to us all, we decided to limit the amount of new stuff that we needed to learn. We chose to stick with plain servlets wired with Google Guice, which is how we build our Java apps now. We use SolrJ, the Java Solr library, to talk to Apache Solr, Joda-Time for date time manipulation and Mockito for unit test mocking (this worked fine with Scala code too). Sometimes we consciously chose to stick with what we knew to ensure timely delivery: the XML formatted endpoints are generated not using Scala's excellent XML support, but using javax.xml.stream.XMLStreamWriter just as we would in Java code. We'd already written this before moving to Scala; it worked, it was readable, so we left it. However, we did switch to use the excellent JSON library from Lift - lift-json - to generate the JSON formatted endpoints as the code was far clearer than with the Java JSON library we were using.
What IDEs do you use for development? What is Scala IDE support like?
We use Jetbrains IntelliJ IDEA 10, some of us use the community edition and some use the ultimate edition. The Scala plugin is pretty good but not perfect. Code completion, find usages, and similar navigation nearly always works just fine. It's not as good as Java at red highlighting code that isn't valid, and we had some problems with it finding ScalaTest test methods, but other than that we were in our familiar environment working as we always had, just in a much more powerful language.
I'm assuming the majority of the developers on the project were Java programmers? How easy did the developers on the project find learning Scala?
Yes, all of us were quite experienced Java programmers. The initial team of four had huge fun learning Scala: often one of us would come in raving about this new Scala feature we'd discovered and sharing it with the rest of the team. We had a buzz that had long been missing in our Java development. Because we were all learning together, this worked really well. In the first couple of weeks, though, there were occasions when we'd be battling to implement something in a good Scala way and couldn't figure it out. Knowing you could just churn out the Java code made this particularly frustrating. There were a few days where we went home in frustration saying, "We're going back to Java tomorrow". Each time, a fresh look in the morning was all it needed to move on. Since then, we've had around ten other Java devs move to pick up Scala. As always, people learn at different speeds and in different ways, but all have come through that and nearly all now get frustrated when they have to write Java code.
One of the things we compare learning Scala against is moving to a different platform like Python/Django or Ruby on Rails. With Scala, at least 75% of what you're working with is the same as in Java. You can use the same libraries and IDE, the way you package jars and wars is the same, your runtime environment and runtime characteristics are the same. A good Java developer can learn to write Java-style code in Scala in a day, then they learn the power of closures and implicit conversions and very soon they're more productive than they were in Java.
One of the common criticisms of Scala as a language boils down to it being too complex. A lot of the time I think this is really about readability - the idea being that it is easier to pick up someone else's code if it is written in a more rigid language like Java. Do you think the criticism is fair? How do you counter it?
I agree, readability is by far the most important characteristic of a codebase. I don't care whether code is imperative or functional, or is idiomatic Scala or Java-without-semicolons, I only care whether it's readable. When we were learning new Scala features, we chose whether to use them based on whether the intent of the resulting code was more obvious. In one example, we tried using the Scala Either class to eliminate a few If statements: the team collectively concluded that the If statements were more readable, so we dropped the use of Either in that case. It's true that due to the rigidity of Java individual lines of code are always easily understood. But that's rarely the problem in understanding any non-trivial codebase: I don't want to understand the detail, I want to understand the intent. Good class design and OO techniques help address this in Java, but I still often find when reading Java code that I cannot see the wood for the trees. In Scala I have the power to express the intent in a way I rarely can in Java.
For example, the Content API needs to decide whether to return results in XML, JSON or redirect to the HTML explorer. We support a format=query string, adding a .xml or .json extension, and specification in an http Accept header. Here's the code that does that, which I think is a good example of how Scala's power aids expression of intent (it's just chaining calls to Scala's Option class):
def negotiateFormatParameter =getParam("format").
orElse(getExtension).
orElse(getExtensionFromAcceptHeader).
getOrElse("html")

There's also a good case that readability is at least partially a function of how much code you have to read. My Java code tends to end up with lots of lines of code unrelated to the problem I am trying to solve, whether this be null checks, getters & setters, constructors for dependency injection or manipulating collections. All of these problems have much more concise expressions in Scala. Of course, much of this can be autogenerated by your IDE, but when reading your codebase I still have to read your constructor and your getters and setters to see if you've customised them.
A classic example is to compare a simple class in Java and Scala:
Java:
public class WelcomeClass {
    private String name;
   
    public WelcomeClass(String name) {
        this.name = name;
    }
   
    public String sayHello() {
        return "Hello " + name;
    }
}

and in Scala:
class WelcomeClass(name: String) {
    def sayHello = "Hello " + name
}

The Java version has to tell me that name is a String three times and it mentions "name" five times. The Scala version mentions "name" only twice, and only says it's a string once. Of course this is a trivial example, but it's symptomatic of what we've found in Scala: less boilerplate code and less needless repetition means fewer trees and more wood, i.e. it's easier to see the intent, not just the detail.
I tend to find that when reading an individual line of code in Scala it sometimes takes a little longer to understand how it's working, but this is more than made up for by the drastic reduction in the number of lines of code.
Sticking with complexity for a moment, do certain aspects of the language - I'm thinking here mainly about things like symbolic names and implicits - cause problems in real-world usage?
Actually implicit conversions really helped us. As I mentioned, we use the SolrJ Java library to talk to Solr, which is an excellent library but, as a Java library, it loves returning nulls. To avoid null checks littering our codebase, we implicitly convert key classes to ones which have more Scala-like methods. So far from causing problems in real-world usage, it actively solves them. In addition, the IntelliJ Scala plugin now understands implicits in nearly all cases, so if you're not sure what's happening control+click will take you to what's actually being called. We've tended to steer clear of heavily symbolic libraries and using symbols for method names, but I think this is an important feature of the language, which like any feature is possible to over-use. Sometimes it makes sense: our method to extract query strings from the http request is called "?", which reads really well in the code. Much more than in Java, the great power of Scala brings great responsibility to focus on whether you're making the intent of your code easier to read. Just because that power can be misused doesn't mean I don't want the power.
Another concern for using Scala in enterprise applications is that each new version seems to break backwards compatibility - so programs compiled against Scala 2.8 are not compatible with binaries compiled earlier and so on. How significant do you think this is? How do you manage incompatibilities within Scala projects?
We started off writing to Scala 2.7.7, and migrated to both 2.8.0 and 2.8.1 soon after they were released. It was pretty painless; the 2.8.0 migration took less than a day (and that was only because I wanted to eliminate the deprecation warnings) and 2.8.1 was drop in. All of the libraries we were using already published versions for multiple Scala versions so that all just worked. The only time it was painful was when, on my personal projects, I was using 2.8 pre-releases. But then, it was my choice to use clearly labeled pre-release code.
We tend now to use simple-build-tool for Scala projects instead of Maven, which makes it easy to release internal libraries for multiple Scala versions.
I'd much rather face some incompatibility when I choose to upgrade than face the situation in Java where some things are never changed and can never be changed. The commonly used HttpServletRequest.getHeaders still returns a java.util.Enumeration, which was effectively deprecated in Java 1.2.
What is the situation with regards finding programmers to continue supporting the Scala code - are good Scala programmers as easy to find as good Java programmers for instance?
We primarily recruit good software developers, rather than looking specifically for Scala developers. We tend to find that good web software developers are polyglot in outlook and have often at least played with Groovy, Scala, Clojure, Ruby or Python. Such people have usually relished the opportunity to work with Scala.
About how much Scala production code is guardian.co.uk running today?
The core codebase behind guardian.co.uk - the one on a two week release cycle - as of two weeks ago has one single Scala class within it. We've maintained a self-imposed no-Scala rule on that codebase until recently, just to be sure we're fully ready as a team to embrace Scala (and to stop me rewriting it). However, many different parts of the site are now driven by Scala microapps including Search (which is written in Scala with Lift), Most Viewed, Punctuated Equilibrium Mystery Bird and the related content component on every article page.
Furthermore, our new identity platform, under development but with its first iteration in production, is written in Scala.
InfoQ: Will you be using more Scala code in the future?
We've found that Scala has enabled us to deliver things faster with less code. It's reinvigorated the team. We'll continue to use the right tool for the job whether that be Scala, Python, .NET, PHP or Bash. In the last six months, all of the new JVM-based projects have used Scala and none have selected Java. I can't see us starting any new project in Java now, especially given the disappointing feature set and timeframe of Java 7.
For developers interesting in learning the language Tackley recommended "Programming in Scala" by Martin Odersky et al. The 2nd edition covers Scala 2.8. He also told us
We found using the Scala REPL (command line) was a good way to experiment with writing Scala code. And, despite what others may say, don't fear just using Scala as a better Java-without-semicolons in the first few days, weeks or months. You'll be missing out if you end your journey here, but it's not a bad phase to go through. Keep learning and embrace features of the language incrementally. The ability to do this is what I think makes Scala unique as a next step for Java developers.
Besides the technical aspects, guardian.co.uk's Content API, and the broader Open Platform suite of services of which it forms a part, is interesting from a business point of view, since it represents a very different approach from that favoured by a growing number of quality newspapers in the UK and elsewhere, ie to place their content behind paywalls. To date The Financial Times, and News International's Times and The Sunday Times have all decided to go down this path, and more recently The New York Times has started to roll-out a paid content model. Veteran BBC journalist John Humphrys argued in The Sun, a tabloid News International paper, that "Good journalism has to be paid for, just as we have to pay for the plumber who fixes a leak, or it will not survive". Tackley however, takes a different view
We firmly believe that the future of digital publishing is to engage and integrate with the rest of the web, not to retreat from it. The Content API is able to extend the reach and brand of the Guardian into significant areas that we would otherwise not be able to reach. This is helped by third parties and partners who use the API, as they can invest in an area and use the relevant Guardian content.
We have a number of different tiers of access to the Content API: without registration, you can access content metadata but not the actual content, with a limited QPS (queries per second) rate. After registration, you can access the article bodies, which include embedded adverts, again with a limited QPS. At the top tier, you become a partner of the Guardian and we agree an appropriate commercial agreement.
A good example partner is WhatCouldICook.com, built by a small independent developer. This site is a good example of tight integration with Guardian content: it uses the API to extract and parse all the recipes we publish and present them in a great way for people wanting to cook. Furthermore, our readers benefit because we include functionality from whatcouldicook.com on our site, see for example the recipe search on the right hand side of the Guardian website.
Our wordpress plugin, built on top of the API, enables any wordpress user to include related Guardian content on their blog.
This level of innovation in specific areas is something that simply would not happen without the Content API. Furthermore, we extensively use the Content API for Guardian-driven projects to aid our rate of innovation: site features like search and zeitgeist, our mobile site and our iPhone app are all driven by the Content API.

For more information have a look here

Scalathon

April 6th "official" announcement of Scalathon, even though people have been
 eagerly tweeting about it for days now.
 
Scalathon is an opportunity for the Scala community to come together and improve the Scala ecosystem over two jam packed days.

Scalathon will be held July 16-17, 2011 at the University of Pennsylvania in Philadelphia.

Scalathon is about code

Scalathon is collaborative

Scalathon is social

Scalathon may be for you if

  • You’re looking to get involved in an exciting project.
  • You’d like to improve your Scala by working with the best developers from around the world.
  • You’re looking for new collaborators on your existing project.
  • You think Scala could be better documented.
  • You want to promote your awesome library.

Event outline


Saturday

Saturday we’ll be hacking all day, 10am-10pm. Throughout the day there will be short talks in the auditorium by representatives of various Scala projects. These talks are all about welcoming newcomers to the project. Many of these talks will:
  • highlight bite-sized bugs appropriate for new contributors
  • give a crash course on the project’s source code
  • describe the project’s build-modify-distribute chain
We are hoping to provide breakfast and lunch, funding permitting.
At 10:30pm anyone with the energy can head over to a local pub for a happy hour.


Sunday

Sunday we’ll be hacking 10am-5pm. Throughout the day there will be enrichment talks in the auditorium. These won’t be the kind of academic talks you would see at Scala Days. Instead, they will focus on Scalathon’s goal of helping Scala developers contribute to the language and its libraries. Many Sunday talks will be tutorials on:
  • advanced functional programming patterns
  • Scala internals
  • software best practices
  • open source dynamics and community building
  • essential software skills
For more information have a look here

Tuesday, April 5, 2011

Tech Talk - Intro scala

Scala fuses object-oriented and functional programming in a statically typed programming language. It is aimed at the construction of components and component system.It smoothly integrates object-oriented and functional programming.

It is designed to express common programming patterns in a concise, elegant, and type-safe way. Scala introduces several innovative language constructs. For instance:
    • Abstract types and mixin composition unify concepts from object and module
      systems.
    • Pattern matching over class hierarchies unifies functional and object-
      oriented data access. It greatly simplifies the processing of XML trees.
    • A flexible syntax and type system enables the construction of advanced li-
      braries and new domain specific languages.

At the same time, Scala is compatible with Java. Java libraries and frameworks can be used without glue code or additional declarations.

Simple Example

As a first example, we will use the standard Hello world program.It is not very fascinating but makes it easy to demonstrate the use of the Scala tools without knowing too much about the language. Here is how it looks:

object HelloWorld {
  def main(args: Array[String]) {
    println("Hello, world!")
  }
}

The structure of this program should be familiar to Java programmers: it consists of one method called main which takes the command line arguments, an array of strings, as parameter; the body of this method consists of a single call to the predefined method println with the friendly greeting as argument. The main method does not return a value (it is a procedure method). Therefore, it is not necessary to declare a return type.

What is less familiar to Java programmers is the object declaration containing the main method. Such a declaration introduces what is commonly known as a singleton object, that is a class with a single instance. The declaration above thus declares both a class called HelloWorld and an instance of that class, also called HelloWorld.

This instance is created on demand, the first time it is used.
The astute reader might have noticed that the main method is not declared as static here. This is because static members (methods or fields) do not exist in Scala. Rather than defining static members, the Scala programmer declares these members in singleton objects.

Compiling this example

To compile the example, we use scalac, the Scala compiler. scalac works like most compilers: it takes a source file as argument, maybe some options, and produces one or several object files. The object files it produces are standard Java class files.

If we save the above program in a file called HelloWorld.scala, we can compile it by issuing the following command (the greater-than sign ‘>’ represents the shell prompt and should not be typed):

> scalac HelloWorld.scala

This will generate a few class files in the current directory. One of them will be called HelloWorld.class, and contains a class which can be directly executed using the scala command


Running the example

Once compiled, a Scala program can be run using the scala command. Its usage is very similar to the java command used to run Java programs, and accepts the same options. The above example can be executed using the following command, which produces the expected output:

> scala -classpath . HelloWorld

Hello, world!

To get more information,tutorial,doc about Scala, have a look Scala official link.