Thursday, June 26, 2014

Scala - Brief overview and getting started

Introduction

Scala has been around for quite some time now, matured into a strong platform with its own ecosystem involving Typesafe, PlayFramework,Akka IO library and slowly becoming the defacto standard to new breed of reactive applications aligning closely with the reactive manifesto.

There are numerous posts, tutorials. documentation on Scala available on the internet and since it aligns closely to Java syntactically its easy to get started, as I dive into Scala I will attempt post core concepts, fundamentals.  

Scala documentation and references are nicely summarized at this link. The ScalaReference document is a good one as well and finally the Scala cheatsheet.

Scala Overview

The Scala language created by Martin Odersky and others at EPFL(École Polytechnique Fédérale de Lausanne) is an Object Oriented and Functional programming language which unifies best of both worlds, Scala is pure Object Oriented Language in which every value is encapsulated by an Object, the types and behavior of the Object is described by declaring a Class. Scala is a functional language in which every value is a function. Scala is a statically typed language that runs on the JVM and seamlessly integrates with Java.
Scala syntax is pretty much similar to Java yet it differs in a few way namely:-
  • Scala is a line-oriented language where statements may be terminated by semicolons or newlines. Scala does not require semicolons; at the end of a statement and are optional.
  •  Scala uses NAME: TYPE syntax for definitions and parameters, while java uses TYPE NAME for declaring member variables or arguments to methods.
  • Scala function definitions start with the def keyword, while in Java we can create methods via the <access modifier> <return type> <name> <arguments> syntax.
  • Scala uses unit for void return types.
  • Scala uses most of Java’s control constructs except for the Java traditional for loop, which it replaces by an enhanced for loop.
  • Comments are same as in Java.
Everything in Scala is an Object, unlike Java there is no concept of Primitive types, and everything in Scala is an Object even functions are Objects.

Numbers are Objects:
Example: 2 + 2 * 3 (These are all Objects being manipulated + and * are methods calls on Integer types)

Functions are Objects:
Example: def doSomeAction(time: Double) {while (true){ callSomeFunction(time)}}

Scala Identifiers

Scala Identifiers/variable names can be of the following types:
  • Alphanumeric Identifiers can start with a letter or an underscore and then be followed by arbitrary sequence of letters, digits and underscore character.  Scala follows Java’s convention of camel-case identifiers.  

          Example: someIdentifierName, a , a_, _a, ab_123 etc… 
  • Operator Identifiers consist of one or more operator characters. These are generally use to exp

           Example: + ++ ::: <?> :> ->  
  • Mixed Identifiers consist of alphanumeric identifier followed by an underscore character and an operator identifier. 

          Example: somevar_=  , this defined an assignment operator.
  • A literal identifier is an arbitrary string enclosed in back quotes (`   `).

          Example: `Y` `<someInit>` `stop`

The following names are reserved words in Scala:
abstract
case
catch
class
def
do
else
extends
false
final
finally
for
forSome
if
implicit
import
lazy
match
new
null
object
override
package
private
protected
return
sealed
super
this
throw
trait
try
true
type
val
var
while
with
yield
_
:
=
=>
<-
<:
<%
>:
#
@


Scala Literal Types

Scala Literal types are similar to Java Wrapper classes as there are no primitives in Scala, valid literal types in Scala are:
scala.Double
scala.Float
scala.Long
scala.Int
scala.Short
scala.Byte
scala.Boolean
scala.Char
scala.Unit which represents a void type
scala.Null which represents a null reference
scala.Nothing which represents an empty type

Scala Operator

The following are operators supported in Scala with similar meaning to the operators in Java.
|
^
&
< 
> 
=
!
:
+
*
/
%

Operators are usually left-associative, i.e. a + b + c is interpreted as (a + b) + c. The only exception to that rule is operators ending in a colon which are right- associative i.e. a :: b :: c is interpreted as a :: (b :: c). Right operators also behave differently with respect to method lookup, normal operators take their left operand as receiver, right-associative operators take their right operand as receiver i.e. List consing/concatenation sequence a :: b :: c is treated as equivalent to a.::(b).::(c).

Scala Classes

Every class in scala inherits from the scala.Any class. There are two sub-classes that derive from the scala.Any class i.e. scala.AnyVal subclass for values classes (i.e. most of the Scala Literal types Double, Float, Int, etc.) and the scala.AnyRef subclass for all reference type classes (i.e. Object, Sequences ).
Scala automatically generates setters and getter methods for variable definitions in a class.
Example:
var x: Int
def x: Int
dex x_ = (x1: Int): unit

Scala has a notion of primary constructor and secondary (auxiliary constructor). 

Primary constructor is the class’s body and parameters list come right after the class name

Example:
class Account(id: Long, startBalance: Double){
….
}

Secondary (Auxiliary) Constructors  are created by defining methods named “this” within the class body there can be as many auxiliary constructors as need but there is a catch, the auxiliary constructor must call the auxiliary constructor defined before it or the primary constructor. Auxiliary constructors end up invoking the primary constructor directly or indirectly.

Example:
class Account(id: Long, startBalance: Double){
     var interestRate: Float = 0
     def this(id: Long, startBalance: Double, interestRate: Float){
  this(id, startBalance)
  this.interestRate = interestRate
     }
}

Scala var and val

var is used for variables in Java terms these are of non-final types and are mutable.
val  is used for constants in Java terms these are of final types and are immutable.

Scala Class definition:


Scala Functions:

Scala functions are similar to methods in Java and following the following definition semantics.



With some very basic understanding let us get into writing some Scala, which is the only way to learn any new language - writing code.

Details on download and installation of Scala can be found on the Scala site ,

Scala Interpreter 
The quickest  way to get started with Scala is by using the Scala interpreter or Scala REPL (Read Evaluate Print Loop) which  is an interactive shell for writing Scala expressions and programs, Simply type expression into the interpreter and  it will evaluate and print results. This is not only a quick and dirty way for testing simple expression but also can be used to run Scala scripts and Scala applications.



The :help command will list available options for the Scala REPL:- :type, :reset, :replay, :cp, :imports and :quit being some of the useful ones.



When you type expressions on the REPL the REPL will print the Result: Type = Value.



Lets define a simple function to check if number is odd or even and execute it in the Scala REPL.

Typing :reset will clear all definitions.



Lets look at the for each and for loop in Scala, first we define an Array of  String elements and then execute if with concise for loops.

Scala Projects 

The scala REPL is good for quick expressions and executing scala scripts, however to write, debug scala application we need something more this is where the ScalaIDE comes useful. Scala IDE can be installed as an eclipse plugin or can be be as standalone IDE.

Details on installing the ScalaIDE plugin can be found on the Scala IDE site

Scala Project Using SBT:

SBT (Scala Build Tool) is the preferred way to run and build Scala applications and modules, unfortunately there is no simple mechanism to get started with an empty blank project similar to maven archetypes. There are other alternatives like giter8 or similar github projects which are individual efforts to make things simpler but not the real thing, I wish sbt had a simple init command which could create an empty blank Scala project Googling around found this post which looks like a viable option.

General steps in getting started with SBT Scala Project :
  1. Install and configure SBT referring to the SBT documentation.
  2. Create the base project directory, example: SimpleScala
  3. Navigate to the project directory and start sbt 
  4. Update the project name via the set name :="SimpleScala" command
  5. Update the Scala version via the set scalaVersion :="2.11.1" command
  6. Set the project version via the set version :="1.0" command
  7. Save the session via the session save command
  8. Exit out of SBT.
  9. Create a file called plugins.sbt inside SimpleScala/project and add the following contents addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.2.0")
  10. Execute the sbt eclipse command.
  11. Base project projects src/main src/test with java and scala folders are generated and project is ready to be imported into eclipse.



Another good post about using SBT to configure projects in Eclipse is found here.

Scala Project Using Maven:

Scala projects can also be created using the maven scala-tools archetypes, which is quite old and has not been updated lately. The maven scala archetype does get some of the initial configuration but needs pom updates, especially updating repositories and scala version and deleting some generated files manually. The preferred way would be the SBT way to work with Scala projects and alternatively add the pom.xml manually to the project.

Use the following command to create and empty maven scala project.

mvn archetype:generate -DarchetypeGroupId=org.scala-tools.archetypes -DarchetypeArtifactId=scala-archetype-simple  -DremoteRepositories=https://oss.sonatype.org/content/groups/scala-tools -DgroupId=com.malcolm.scala -DartifactId=SimpleScala -Dversion=1.0-SNAPSHOT -DinteractiveMode=false

(Please replace groupID and artifactId)



Importing the maven project into the IDE will display some errors, basically related to older version of scala compiler. 



You would need to update the pom and remove the scala test files generated under the test folder. This should pretty much give you a clean eclipse maven project. 


 

Gets kind of messy many pom updates and deleting generated files.

There are some limitations working with ScalaIDE in terms of the version of Scala you can use, ScalaIDE is tied to a specific version of Scala as of writing this blog the current version of ScalaIDE  is available for Scala 2.10.x and 2.11.x versions but you need to pick up the correct bundle, one can  also take a chance with the milestone release which may offer better flexibility in maintaining different versions of the Scala library.

As recommended SBT is a good choice for working with scala projects, the build.sbt lets you speciy the scala version and dependencies.


Until next time,
Malcolm


Back to Scala Thoughts

No comments:

Post a Comment