Advanced features in Scala talk

From the land of scala Daniel Spiewak one of the very rare, who are able to explain things in simple relative terms. In this talk, Daniel talks on an advanced features in Scala.. especially, Scala’s type system which to many appears very complex, but daniel in this video breaks the ice a little..

BIG THANKS TO THE GUYS AT JAVA ZONE FOR SHARING.

A Scala API for database proceedings (ScalaQuery)

Back in the days making calls or connections to a database with jdbc took this much:

(Below is an excerpt code i wrote in 2005… :( )

Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "dblocal";
String driver = "com.mysql.jdbc.Driver";
String user = "dbuser";
String pass = "dbuser";
try {
  Class.forName(driver);
  con = DriverManager.getConnection(url + db, user, pass);
  System.out.println("jdbc driver for mysql : " + driver);
  System.out.println("Connection url : " + url + db);
  System.out.println("Connection is established...");
  con.close();
  System.out.println("Connection is closed...");
} catch (Exception e) {
System.out.println(e);
}
 
The level of abstraction here is very low.
Then came ORM’s with some abstraction but also giving us leaving us with the mountain to climb whilst leaving us with the vietnam war of the impedance mis-match.

The capability of OOP (imperative) programming languages to tackle high-level concepts like relational algebra has been questioned, this obviously has given room for Functional programming languages to shine.

One of such i recently have found within the JVM space is ScalaQuery. I stumble across this on twitter, and began to look closer, though being a Scala fan and community member i had heard of ScalaQuery in it's early days, but did not take any real interest.

With the API in question connection to a database is more concise with named/default arguments (parameters) from scala land:

import org.scalaquery.session._
import org.scalaquery.session.Database.threadLocalSession

val db = Database.forURL(
  "jdbc:mysql://localhost:3306/",
  driver = "com.mysql.jdbc.Driver",
  user="dbuser",
  password="dbuser"
)

ScalaQuery takes a better object oriented approach when mapping objects to tables:

import org.scalaquery.ql.extended.{ExtendedTable => DBTable}
import org.scalaquery.ql.TypeMapper._
import org.scalaquery.ql._

case class Country (id:Int, name:String)
val Country = new DBTable[(Int, String)]("countries") {
    def id = column[Int]("id", O.NotNull, O.PrimaryKey, O.AutoInc)
    def name = column[String]("name", O.NotNull, O.DBType "varchar(50)")
    def * = id ~ name
  }

OR 

object country extends new DBTable[(Int, String)]("countries") {
    def id = column[Int]("id", O.NotNull, O.PrimaryKey, O.AutoInc)
    def name = column[String]("name", O.NotNull, O.DBType "varchar(50)")
    def * = id ~ name
  }
 

Now one of the uses of case classes i love the most is using it as a value object, because with a case class we get the equals, hash and toString methods for free.

case class Country (id:Int, name:String)
val countries = List(
    Country(1, "Nigeria"),
    Country(2, "United Kingdom"),
    Country(3, "United States of America"),
    Country(4, "Canada"),
    Country(5, "France"),
  )

With the above playing with a dataset from the database becomes fun, as scala provides a collection library that is pack with goodness..

The following Query with for comprehensions.

val nigeria = for {c <- countries if c.id == 1}yield c.id ~ c.name

happy days... only now i have to look for some project to use it in.

ScalaQuery Slides 2011 by Stefan Zeiger

Emacs (starter-kit and emacs for Mac OSX), Scala and Ensime Configuration steps

(Before starting with this i think you may want to delete the~/.emac, ~/.emacs.d or ~/.emacs~ files from you computer, if they already exit. this is just my view.. reason being that the settings in the .emacs file.. i noticed overshadowed the settings in the emacs start-kit version.)

NB: Note that, this is my cloned copy and is specific to my system and user name.

This post aims to guide you through the steps and get you setup based on my cloned copy.

To get cracking with this, type the following on the terminal: clone this git repo with the following:

git clone git@github.com:kengimel/emacs-dotfiles.git .emacs.d
ln -s .emacs.d emacs.d
cd emacs.d

next rename ikenna.el to your username on a mac that will be you shortname: the command below will give you the current username
 whoami    # this will return to tell you your current username
 mv kengimel.el yourusername.el

next rename kengimel.el to you system name, this can be gotten by typing:
 hostname                # this will return to tell you your current hostname / system name
 mv ikenna.el yourhostname.el

Sometimes the hostname may appear verbose use this command to rename it, if you rename it don’t to repeat the step above:
 scutil --set HostName yournewhostname

NB: you have to restart your machine for this to take effect

Next:

 git submodule init 
 git submodule update 

The commands above will update the ensime submodule for the project:

Next download and install emacs for Mac OSX.

 cd vendor/ENSIME 
 sbt update               # this may take a little while to come through
 sbt dist
 Stop existing ENSIME server by killing inferior-ensime-server buffer 
 Restart ENSIME with M-x ensime 
 M-x ensime-sbt #gives you ensime sbt goodness
 M-x eshell #gives you the already embedded command line terminal

Next open Applications folder and click Emacs.app to start emacs for Mac (You may notice that ensime will throw an error, don’t worry just carry out the next steps below)

C-x C-f (control-x and control-f) and open the file with you system name Locate this line (i guess this will be around line number 151) (add-to-list ‘load-path (concat dotfiles-dir “/vendor/ENSIME/elisp”)) and edit it to this (add-to-list ‘load-path (concat dotfiles-dir “/vendor/ENSIME/dist/elisp”))

DOWNLOAD SETUP THE FOLLOWING EMACS MODES:
NXML-MODE
AUTO-COMPLETE MODE

I advice to first try out your installation by debugging it with this command;

 emacs --debug-init 

And now you ready to start writing some wonderful concise scala code with the help of emacs ENSIME. kudos to the guys behind the emacs starter kit, technomancy, george agnelli, topfunky and aemon cannon.

ROCK ON !

Converting Java List to Scala List

I am currently playing around with some legacy Java libraries and at some point i needed to convert a Java List to a Scala List, because, i have come to prefer using Scala’s very rich set of functions like filter(), find(), foreach(), foldLeft(), flatMap() and map(), which are very handy and concise. :)

As you may know already or according to the documentations, Java’s List is an interface which is conceptual or abstract in nature, while Scala’s List is an implementation of a sequence of elements that follow insertion order and do allow random access to elements within.

I mostly have used Java’s ArrayList, as they are mutable via the add(e) method which alters the existing contents of the list and has constant-time random access.

Scala’s List is an explicit implementation of a sequence. It is imported by default into scope as an immutable linked list i.e. it’s state cannot be modified after it has been instantiated and operations requiring random access take linear time.

Based on the above Scala’s List is not similar to Java’s List or ArrayList and as such can’t serve as a replacement for them.

After a little while on the REPL and going through documentations:


scala> var jList = new java.util.ArrayList[String]()
jList: java.util.ArrayList[String] = []

scala> jList.add("Ikenna"); jList.add("okpala"); jList.add("kengimel"); jList.add("Scala"); jList.add("Java")

scala> println(jList)
[Ikenna, okpala, kengimel, Scala, Java]

scala> val slist = scala.collection.JavaConversions.asBuffer(jList)
slist: scala.collection.mutable.Buffer[String] = Buffer(Ikenna, okpala, kengimel, Scala, Java)

scala> println(slist.toList) 

List(Ikenna, okpala, kengimel, Scala, Java)            #However, i noticed that this implicitly converts the Java List  to a mutable buffer, as you may have noticed on line 12, i used the toList function to convert it to a Scala List. 

scala> println(jList)
[Ikenna, okpala, kengimel, Scala, Java]



One of Scala’s goal is to make code as concise and functional as possible. Included in Scala 2.8 library are already baked Java to Scala conversions.
These implicit functions are found in the scala.collection.JavaConversions package to assist the conversion of Java’s List to Scala.List. All that is required is importing this package into scope and you are already benefiting from these silent actors.

import scala.collection.JavaConversions._

Also in this mode, i observed that this converts the Java List to a Buffer (i.e. scala.collection.mutable.Buffer) that extends Seq[A], as you may have noticed on line 12 above, i used the toList function to convert it to a proper Scala List, this may be an option that you may consider in your program.

Prior to Scala 2.8 version(2.7.*) this was achieved by an implicit conversion:


implicit def toScalaListFromJavaList[T](jList: java.util.List[T]) : Seq[T] =
new BufferWrapper[T]() { def underlying = jList }

There appears to be more grounds to cover, feel free to provide your views on this post.

CIAO for now.

SBT and Netbeans Terminal Emulator..

One of the new features that came bundled with Netbeans 6.9 is the terminal emulator. This provides a shell scripting interface for Netbeans users. This has been very useful especially with running build tools like maven from the terminal emulator without having to navigate out of the IDE.

To access this feature, go to ‘Window > Output > Terminal. For more on the Netbeans Terminal Emulator click here

SBT (simple build tool) appears to be one of the raves of the moment, it gradually has grown on me and i am using it in my current project which obviously is Scala based.

At the moment i do not know of any plugin for SBT on the Netbeans platform.

I Initially assumed that having successfully installed SBT on my computer that it would be easily accessible from the terminal emulator. But ‘Lo and Behold’ the Netbeans terminal emulator was not aware of SBT‘s location.

In order to get SBT running in the terminal emulator the following commands would be appropriate, especially for MAC or Unix based PCs and already have SBT running. If you don’t have SBT running already click here to set it up.



sudo echo "java -XX:+CMSClassUnloadingEnabled -XX:MaxPermSize=256m -Xmx512M -Xss2M -jar /include/here/path/to/the/sbt-launcher.jar \"\$@\"" | sudo tee /usr/bin/sbt #please don't forget to change the /include/here/path/to/the/sbt-launcher.jar to the relevant path on your system that points to the sbt launcher jar file.

whoami # this would tell you the current user if you already know the name skip this

cd /usr/bin # navigate to the /usr/bin folder

sudo chown username sbt # change owner to the required username on sbt. Also remember to change the username here  to the relevant one on you want to use
or alternatively

sudo chmod u+x sbt # this will give the required operation permission to the user

After this has been done navigate back to your Netbeans IDE’s terminal emulator and type sbt to enjoy it’s goodness within the Netbeans IDE.

CIAO for now..

Scala and Lift Web Framework.. My 2 Cents.

This blog post will most likely appeal to Scala headed and Lift handed programmers, so if you don’t fall into this category… You have been warned ! :)

Scala is an acronym that stands for SCAlable LAnguage. It is a statically typed functional and object oriented programming language that runs on the Java Virtual machine (JVM) and the .NET common language runtime (CLR). It has this feel of a truly dynamically typed language but really it is not dynamically typed.

Scala on its functional side is a branch of the ML languages (example: Haskell), they are known to be strongly typed unlike their homoiconic and dynamically typed functional language counterpart like LISP or Dylan.

The main principle of Scala is that functional programming complements object oriented programming, despite the surface contradictions. Functional programming places her emphasis on immutable values and side effect free functions as opposed to object oriented programming which is all about state that is mutated in objects and methods that can modify state that are out of their scope. But combining these two paradigms in Scala has proven to be worthwhile. Scala makes it possible to create immutable objects and also apply OO goodness. In Scala, every value is an object and every function an object. (Wampler, D., 2008)

The core advantages of Scala are:
Scala is functional which helps to write lesser and more concise code making it easier to test and maintain.
• Because Scala is functional in nature it embraces a lot of mathematical concepts, which emphasise correctness from a logical point of view. This is very important and infact can help reduce bugs in the software system.
Scala introduces better ways of doing object oriented programming, in terms of composability (using mixins and traits) and scalable design.
Scala provides a better model and much more principled approached for dealing with concurrency issues. Scala provides an Actors library that is similar to the one in Erlang. Actors are nothing more than concurrent process actions that communicate by exchanging messages. Actors can also view as active objects, based on this a method call corresponds to sending a message. The Scala Actors can also do asynchronous and synchronous messaging.

Lift is a non-mvc web framework written in Scala. Lift‘s approach to web development, is coined “view first“. With this approach a component of web page is an instance of a Scala object, these are called snippets in Lift.

Snippets basically are bindings between the view and a function that could contain some business logic and primarily transforms input XML to output XML or put in another way renders dynamic or interactive feedback to the View Template. In the view any tag with the Lift namespace is a snippet(Pollak, 2010).

<lift:someclass.function/> #binding to a function
or
<lift:someclass/>  #binding to a render function... if defined will be displayed on page load by default.

They could be easily mistaken to be controllers (like i did :( ), but they are not.

So far it appears that Lift is elegant and has a productive sensation. I appreciate the fact that it does a lot of the plumbing for me, especially with regards to form rendering and security etc….

This is a web framework that i feel possesses elements of rhythm, tempo, melody, harmony, timbre, articulation, and dynamics. It leverages the power of Scala‘s xml and actors libraries also.

And because Lift is based on Scala, it is possible to play with legacy java code seamlessly and combine both functional and OO features like pattern matching, closures and high order functions etc.

Lift is one of the reasons why Scala is here to stay !

Almost all web applications i have been involved with have had varying numbers of web forms. Usually the state of these web forms are required to be maintained across instances.

This provides valuable information on the status quo and offers varying forms of feedback to users, hence it be referred to as a user friendly application.

Alright, enough chit chat, let’s look at some code. I have previously used this same use case while introducing my self to other web frameworks, but found it to be more intriguing with Lift.

In the following example, I use a simple video rental form application to highlight some of Lift’s features. Hopefully you got maven and Git installed, You can find the full source for this example here on Github and also a working example here.

The Web.xml has got very little mark up in it that points to the LiftFilter class and defines the URL pattern.


<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<filter>
  <filter-name>LiftFilter</filter-name>
  <display-name>Lift Filter</display-name>
  <description>The Filter that intercepts lift calls</description>
  <filter-class>net.liftweb.http.LiftFilter</filter-class>
</filter>
 <!--  <init-param>
<param-name>bootloader</param-name>
<param-value>path to my custom Boot class</param-value>
</init-param>  -->

<filter-mapping>
  <filter-name>LiftFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

</web-app>

All lift application must have a Boot class. This is basically an expressive configuration class where lift allows you to define Rules that modify lift’s environment. Lift also allows defining a custom Boot instance using the init param tag, this custom Boot class must extend Bootable class and provide implementation for the boot method. The boot method can run only once.

class Boot {
  def boot {

    // where to search snippet
    LiftRules.addToPackages("com.liftforms")

    // Build SiteMap
    val entries = Menu(Loc("Home", List("index"), "Home", Hidden)) ::
		  Menu(Loc("View", List("view"), "View", Hidden)) :: Nil

    // Setting the sitemap
    LiftRules.setSiteMap(SiteMap(entries: _*))

  }
}

The LiftRules.addToPackages methods tells lift where to find snippets. By default you will get this code for free with the maven Lift archetype. URLs in Lift are pretty, the Menu/setSiteMap methods allows your to define meaningful urls for web pages and more.

The snippet class below extends the StatefulSnippet trait. This trait is used to maintain state of the form variables. Lift does not require using HTML tags for form elements directly, instead Lift provides generator functions on net.liftweb.http.SHtml. This allows Lift to set up all of the internal plumbing which kept my code relatively simple to read and separate from the view.

Below is example code for the forms class “RentingForm.scala”. Notice that is extends StatefulSnippet to help it manage state and the “class” -> “required” is used to meet the criteria for the jquery client side validation library. For more on this click here.

class RentingForm extends StatefulSnippet { // RentingForm snippet extending StatefulSnippet
  var dispatch: DispatchIt = {
    case "rent" => rentForm _ // call rentForm function
  }
  var (name, address, email, movieType, dateOfHire, numberOfDays, discount) = ("", "", "", "", "", "", "") // Tuple of form variables
  val movieSeq = Seq("" -> "Select Movie Type", "Sci-fi" -> "Sci-fi", "Horror" -> "Horror", "Comedy" -> "Comedy", "Suspense" -> "Suspense", "Romance" -> "Romance") // Sequence of movie types
  val discountMap = Map("Regular Customer" -> "Regular Customer", "New Customer" -> "New Customer") // Map of customer types

// definition for rentForm
  def rentForm(xhtml: NodeSeq): NodeSeq = {
    dispatch = {
      case name if name != "" => showDetails _                  // call show details function if name is not equal to ""
    }

    val discounts = SHtml.radio(discountMap.keys.toList, Full("New Customer"), discount = _, "class" -> "required") // radio button

    val submitLabel = "Confirm"
// Binding Form fields and components to template
    bind("v", xhtml,
      "name" -> SHtml.text(name, name = _, "class" -> "required"), // text field
      "address" -> SHtml.textarea(address, address = _, "rows" -> "5", "class" -> "required"), // text area
      "email" -> SHtml.text(email, email = _, "class" -> "required email"), // text field
      "movie" -> SHtml.select(movieSeq, Empty, movieType = _, "class" -> "required"), //  select options combo box
      "date" -> SHtml.text(dateOfHire, dateOfHire = _, "class" -> "required date", "id" -> "datePicker"), // text field
      "numberOfDays" -> SHtml.text(numberOfDays, numberOfDays = _, "class" -> "required"), // text field
      "regular" -> discounts(0), // radio buttons 0
      "new" -> discounts(1), // radio button 1
      "rtxt1" -> (discountMap.head.key), //radio button label 0
      "rtxt2" -> (discountMap.last.key), // radio button label 1
      "submit" -> SHtml.submit(submitLabel, () => {}, "id" -> "submit")) // submit button

  }
// definition for showDetails
  def showDetails(xhtml: NodeSeq): NodeSeq = {

    val submitLabel = "Edit"
// Binding Form fields and components to template
    bind("v", xhtml,
      "name" -> Text(name), // plain text rendering form variable to template
      "address" -> Text(address), // plain text rendering form variable to template
      "email" -> Text(email), // plain text rendering form variable to template
      "movie" -> Text(movieType), // plain text rendering form variable to template
      "date" -> Text(dateOfHire), // plain text rendering form variable to template
      "numberOfDays" -> Text(numberOfDays), // plain text rendering form variable to template
      "regular" -> Text(discount), // plain text rendering form variable to template
      "new" -> Text(""), // plain text rendering "" to template
      "rtxt1" -> Text(""), // plain text rendering "" to template
      "rtxt2" -> Text(""), // plain text rendering "" to template
      "submit" -> SHtml.submit(submitLabel, () => S.mapSnippet("RentingForm.rent", editDetails _), "id" -> "submit")) // submit button

  }

// definition for editDetails
  def editDetails(xhtml: NodeSeq): NodeSeq = {
    val discounts = SHtml.radio(discountMap.keys.toList, Full(discount), discount = _, "class" -> "required") // radio button
// Binding Form fields and components to template
    bind("v", xhtml,
      "name" -> SHtml.text(name, name = _, "class" -> "required"), // text field
      "address" -> SHtml.textarea(address, address = _, "rows" -> "5", "class" -> "required"), // text area
      "email" -> SHtml.text(email, email = _, "class" -> "required email"), // text field
      "movie" -> SHtml.select(movieSeq, Full(movieType), movieType = _, "class" -> "required"), // select option combo box
      "date" -> SHtml.text(dateOfHire, dateOfHire = _, "class" -> "required date", "id" -> "datePicker"), // text field
      "numberOfDays" -> SHtml.text(numberOfDays, numberOfDays = _, "class" -> "required"), // text field
      "regular" -> discounts(0), // radio button 0
      "new" -> discounts(1), // radio button 1
      "rtxt1" -> (discountMap.head.key),  // radio button label 0
      "rtxt2" -> (discountMap.last.key), // radio button label 1
      "submit" -> SHtml.submit("Save", () => S.redirectTo("/view", () => S.mapSnippet("RentingForm.rent", thankYou _)), "id" -> "submit")) // submit button

  }

// definition for thankYou
  def thankYou(xhtml: NodeSeq): NodeSeq = {
    Log.info(name, address, email, movieType, dateOfHire, numberOfDays, discount) // logging the form variables
// Binding Form fields and components to template
    bind("v", xhtml,
      "name" -> (name))
  }

}

Finally, the corresponding web page for the above snippet, also notice that is wrapped around the with the which points to the template file in the “templates-hidden” folder. For more on this click here.

<lift:surround with="default" at="content">

    <lift:RentingForm.rent form="POST" id="confirmform" class="cmxform">

            <fieldset>
                <legend>Video Hire Details</legend>

                <div>

                    <label for="name">Name:<span>*</span></label>

                    <v:name/>

                </div>
                <div>
                    <label for="address">Address:<span>*</span></label>

                    <v:address/>

                </div>
                <div>
                    <label for="email">Email:<span>*</span></label>
                    <v:email/>

                </div>
                <div>
                    <label for="movietype">Movie Type:<span>*</span></label>
                    <v:movie/>

                </div>
                <div>
                    <label for="dateOfHire">Date of Hire:<span>*</span></label>
                    <v:date/>
                    <span id="notify"> DD/MM/YYYY </span>
                </div>
                <div>
                    <label for="numberOfDays">Number Of Days:<span>*</span></label>
                    <v:numberOfDays/>
                </div>
                <div class="radio">
                    <fieldset>
                        <legend><span> Discount Rate:<span>*</span> </span></legend>

                        <div>
                              <v:regular/><label> <v:rtxt1/> </label>
                             <v:new/> <label> <v:rtxt2/> </label>

                            </div>

                    </fieldset>
                </div>
                <div id="btn">

                      <v:submit/>

                </div>
            </fieldset>
    </lift:RentingForm.rent>
</lift:surround>

For the full source code on this example:

 git clone git@github.com:kengimel/Lift_forms.git 

and also a working example here.

 

REFERENCE:
Odersky M. et al, 2008. Programming in Scala First Edition, Artima.
Pollak D, 2010 Scala Lift Off London, Q&A, Available at: http://skillsmatter.com/podcast/scala/scala-lift-off-david-pollak [Accessed November 2010.]
Wampler, D., 2008. Available at: http://blog.objectmentor.com/articles/2008/08/03/the-seductions-of-scala-part-i [Accessed January 2010.]

Setting Up SBT (Simple Build Tool) on Unix For Building Scala Based Project.

One of the problems that plagued the Java development space prior to the advent of tools like ANT and Maven, was the lack of automated build tools.

Previously, Java developers had to either write thier own build script which knew no unformity at all or do javac *.java (did this really work.. hmm).

But today setting up a Java project is gradually becoming a trivial task especially with tools like Maven and SBT.

SBT is a build tool for Scala based project. SBT integrates very well with Maven.

The feature of SBT, i like is the continuous compilation (~compile) this is very useful especially when testing and/or debugging.

Kudos to the hands behind SBT and Maciej Matyjas for recommending SBT to me..  you guys rock. period !

Alright, lets delve in and set up an SBT build environment.

Firstly, you need to download the latest jar of SBT here

Next create the bin folder and move the SBT jar to the bin folder.

mkdir ~/bin
mv ~/Downloads/sbt-launcher-0.7.4.jar ~/bin

Next create the SBT file.

echo "java -XX:+CMSClassUnloadingEnabled -XX:MaxPermSize=256m -Xmx512M -Xss2M -jar \`dirname \$0\`/sbt-launcher-0.7.4.jar \"\$@\"" | sudo tee ~/bin/sbt

I prefer this way of using “dirname” rather that using a relative or absolute path to the SBT jar file.

After this is done you may need to  change the read write mode for the SBT file.

chmod u+x ~/bin/sbt

This allows you to launch SBT file to run or execute.

Finally, set environment path for SBT, this file name varies across flavours of Unix. I use a Mac OSX 10. 6 and i use .profile or .bash_profile to set my environment path.

For Debian this is .bashrc. Find out the file for setting environment variables for your flavour of Unix.

emacs .profile                              #(or nano .profile or any editor of your choice.. only have it in mind that these type of files are hidden system files)
export PATH=$PATH:~/bin                     #(copy and paste this in to .profile)
source .profile

This allows you to launch SBT from any directory by typing sbt at the terminal.

Type sbt on terminal to enjoy the it’s euphoria.

For more on SBT here

The Higher Order Style.. (Functions)

These past days have been a revealing period, as i wondered into Scala land to behold it’s features that have made it such a hot topic….

My background in programming is largely imperative.. until earlier this year when i started  trying out some functional programming languages (Haskell, F#, Scala.. etc).

One feature of functional languages that i found very interesting were Higher Order Functions.

Higher order functions are notably a vital part, if not the most important part of functional languages.

A higher order function  accepts a function as a parameter or can return  a function back.

An example:

In an imperative language like JAVA looping through characters to find a lowercase value could be:


private boolean hasLowerCase = false;
for(int i = 0; i = title.length(); i++){
if (Character.isLowerCase(title.charAt(i))){
hasLowerCase = true;
break;
}
}

In Scala this can be achieve thus:

val hasLowerCase = title.exists(_.isLowerCase)
or
val hasLowerCase = title.exists(title => title.isLowerCase)

In Scala this is possible because Scala functions are values, this means you can take a function and explicitly set it to a variable.

val areaOfTriangle = (l:Int, b:Int) => l * b / 2
areaOfTriangle(2,3) = 3

This qualifies it to be passed as a parameter to another function.

Scala allows it’s users to define and use Higher order functions, this as shown makes code concise, putting to good use higher levels of abstractions, which to me is awesome:

In Scala playing or looping through Lists appears to be trivial as shown below:


List(3.5, 2.5, 1.5).map((a:Double) => a * 2)
or
List(3.5, 2.5, 1.5).map(a => a * 2)
or
List(3.5, 2.5, 1.5).map(_* 2)

Above the code multiplies the members of the List by 2.. The last two functions rely on the implicit typing capability of the Scala language. This makes the code even less noisy, gives us little to type and gives a similar feel of regular dynamic scripting language as the compiler does all the hard work of type inferencing.

Programming with higher order functions, like the map or exists function makes it;

  • Expressively clear, ease to grasp what the program does and the intention of the programmer.
  • Functions that accept Functions as arguments are more reusable than other functions.
  • Higher order function gives us the needed syntactic sugar to build big functionalites out of tiny bits of code.