Scala

SCALA Extension methods

 

Now those of us that have used .NET for a while that we can create extension methods, which are highly useful things.

If you have been living under a rock or something for the last 5 years or so, here is what MSDN says about extension methods

Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

https://msdn.microsoft.com/en-gb/library/bb383977.aspx

Which we might define something like this in C#

using System.Numerics;
namespace ExtensionTest {
public static class MyExtensions {
    public static BigInteger Square(this BigInteger n) {
        return n * n;
    }
    static void Main(string[] args) {
        BigInteger two = new BigInteger(2);
        System.Console.WriteLine("The square of 2 is " + two.Square());
    }
}}

The question is, can this be done using Scala?

Turns out there are actually a number of ways to do this in Scala.

Let’s see 2 of the most popular ways, which both make use of a Scala feature called “impllicits”

Implicits

Scala implicits are too big of a topic for me to explain in this post. I would recommend you read the Scala manual to get a better understanding of them

 

Way 1 : Implicit Method And Regular Class

The first way makes use of a implicit method and a regular Scala class, here is the code

object MyExtensions {
  class RichInt(i: Int) {
    def square = i * i
  }
  implicit def richInt(i: Int) = new RichInt(i)
}

Which we can use like this

import MyExtensions._

object ClassesDemo {
  def main(args: Array[String]) =
  {


    val theInt = 20
    val theSquaredInt = theInt.square

    System.out.print(s"theSquaredInt = $theSquaredInt")

    System.in.read()

    ()
  }

}


Way 2 : Implicit Class

Since Scala 2.10 it is possible for classes themselves to be implicit, which means we could also write a Scala extension method like this

object MyExtensions {
  implicit class RichInt(i: Int) {
    def square = i * i
  }
}

Usage is the same as above

In addition, it is possible to avoid creating an instance of the extension type by having it extend AnyVal

http://stackoverflow.com/questions/3119580/scala-equivalent-of-c-s-extension-methods

Which means that the new code would look like this

object MyExtensions {
  implicit class RichInt(val i: Int) extends AnyVal {
    def square = i * i
  }
}

Usage remains the same as before

 

Where Do Implicits Come From

If you are looking at this code and wondering how the compiler finds the implicit code this next part taken from the Scala docs may help solidify the answer to that a bit

When the compiler sees the need for an implicit, either because you are calling a method which does not exist on the object’s class, or because you are calling a method that requires an implicit parameter, it will search for an implicit that will fit the need.

This search obey certain rules that define which implicits are visible and which are not. The following table showing where the compiler will search for implicits was taken from an excellent presentation about implicits by Josh Suereth, which I heartily recommend to anyone wanting to improve their Scala knowledge. It has been complemented since then with feedback and updates.

The implicits available under number 1 below has precedence over the ones under number 2. Other than that, if there are several eligible arguments which match the implicit parameter’s type, a most specific one will be chosen using the rules of static overloading resolution

  1. First look in current scope
    • Implicits defined in current scope
    • Explicit imports
    • Wildcard imports
    • Same scope in other files
  2. Now look at associated types in
    • Companion objects of a type
    • Implicit scope of an argument’s type
    • Implicit scope of type arguments
    • Outer objects for nested types
    • Other dimensions

     

So I hope that has shown you that you can indeed use extension methods in Scala too

Advertisements
Scala

Inheritance / overriding / traits

 

In this post we will talk about how to create abstract classes, inheritance and also traits.

<Rant>

One thing I wanted to mention is that in Scala the focus is clearly on creating immutable data structures. Which is what YOU should be trying to achieve WHEREVER possible.

This means that you should be using var sparingly, really think about whether you DO need that field to be mutable, I would say ALWAYS favor val if you can, and only use var as a last resort.

In my last post I did actually show some code that true Scala devs would probably not do which is to accept var as constructor parameters. This was to illustrate a point about properties, but in reality this should have been using val instead.

</Rant>

Anyway rant over. Let’s carry on with the guts of this post, which to start of will be abstract classes.

 

Abstract Classes

In Scala much the same as other OO languages (looking at you here .NET), you can declare a class as abstract using the abstract key word.

Unlike .NET you do NOT mark the individual methods as “abstract”, you only make the class abstract. A method is abstract if the class is abstract and there is no implementation.

Here is an example of an abstract class, with a simple abstract method

//Primary constructor
abstract class PersonBase(val firstName: String, val lastName: String) {

  def ReportsTo() : String

  override def toString: String = {
    s"firstname: $firstName, lastname: $lastName, reportsTo : $ReportsTo"
  }
}

Inheritance

So now that we have an abstract class, how do we extend this abstract class. Lets see a couple of examples that extend the abstract class we specified above.

Here we have a Supervisor and CEO class, both of which want to use the PersonBase class as a super type.

So how do we do that in Scala?

Well it is actually quite simple, let’s see an example of the Supervisor and CEO classes.

class Supervisor(override val firstName: String, override val lastName: String, val budget: BigDecimal)
  extends PersonBase(firstName, lastName)
{
  override def ReportsTo(): String = "MD"
}



class CEO(override val firstName: String, override val lastName: String, val budget: BigDecimal)
  extends PersonBase(firstName, lastName)
{
  override def ReportsTo(): String = "None"
}

There are a couple of things to note above:

  • We use the extends keyword to extend the PersonBase class (which makes PersonBase the super type of the current type (i.e. Supervisor / CEO)
  • We use the override keyword a couple of times in the primary constructor for these new Supervisor / CEO classes
  • We use the override keyword on the method def to override the super types ReportsTo() method

 

In a nut shell that is the basics of how to inherit from a class and override methods / primary constructor parameters

 

Interfaces

In Scala there are no interfaces, instead there are traits. We will look at those next

 

Traits

Traits are like abstract classes, and are used to define object types by specifying the signature of the supported methods. Traits may be partially implemented, and a type may also inherit from MULTIPLE traits. What multiple inheritance, yep you can do that.

Yikes

In contrast to classes, traits may not have constructor parameters.

Lets see an example of a simple trait that mimics a 2 input AND logic gate, which also has a NAND method too.

In this simple example, we have a abstract method “and” which needs to implemented, but we also have a nand method which is already implemented. So the inheritor of this trait ONLY needs to supply an implementation for the “and” method.

trait AndGate {
  def and(x1: Boolean, x2: Boolean): Boolean
  def nand(x1: Boolean, x2: Boolean): Boolean = !and(x1, x2)
}


class LogicGate() extends AndGate {

  def and(x1: Boolean, x2: Boolean): Boolean =
    x1 && x2

}

Which we are able to use like this:

object ClassesDemo {
  def main(args: Array[String]) =
  {

    val lg = new LogicGate()
    val and1Result = lg.and(true,false)
    val nand1Result = lg.nand(true,false)
    System.out.print(s"lg.and : $and1Result,lg.nand : $nand1Result \r\n")

    val and2Result = lg.and(true,true)
    val nand2Result = lg.nand(true,true)
    System.out.print(s"lg.and : $and2Result,lg.nand : $nand2Result \r\n")


    System.in.read()

    ()
  }

}

Which when run looks like this:

image

 

The other interesting thing about traits, is that you may have multiple traits, and they may even have the same method. For example what about this, what do you think happens here:

trait LoggerBase
{
  def log(input : String): Unit
}


trait Logger extends LoggerBase {
  override def log(input : String): Unit = {
    System.out.print(s"Logger :input = '$input'\r\n")
  }
}

trait AnotherLogger extends LoggerBase {
  override def log(input : String): Unit = {
    System.out.print(s"AnotherLogger input = '$input'\r\n")
  }
}


//This class inherits from 2 Traits, both with same
//method implemented
class SomeWeirdLogger() extends Logger with AnotherLogger {

}

Do you think we will see this output

AnotherLogger input = ‘What gives’

or this output

Logger input = ‘What gives’

 

Well we actually get this output

image

But why is this?

What would happen if we reversed the order to this

trait LoggerBase
{
  def log(input : String): Unit
}


trait Logger extends LoggerBase {
  override def log(input : String): Unit = {
    System.out.print(s"Logger :input = '$input'\r\n")
  }
}

trait AnotherLogger extends LoggerBase {
  override def log(input : String): Unit = {
    System.out.print(s"AnotherLogger input = '$input'\r\n")
  }
}


//This class inherits from 2 Traits, both with same
//method implemented
class SomeWeirdLogger() extends AnotherLogger with Logger  {

}



 

Where we have swapped the order of the inherited traits.

Now we get this output. Mmm Strange.

image

Basically traits DO HAVE an order, and the outer most one wins

 

 

 

 

 

 

Scala

SCALA Properties / classes

In this post we will be covering the very basics of how to create properties in our Scala classes, and also talk through how to create simple classes

 

Constructors

Let’s start by creating a very simple class called “Person” that will have a single constructor that take a string for firstname and a string for lastname.

The firstname and lastname should have getters but no setters.

In Scala this is achieved as follows:

class Person(val firstName: String, val lastName: String) {

}

Which we may use like this

object ClassesDemo {
  def main(args: Array[String]) =
  {

    val person = new Person("sacha","barber")
    val theirLastName = person.lastName


    System.out.print(s"Persons last name is $theirLastName")

    System.in.read()

    ()
  }

}

See how we are using val, this means it is immutable, so we only expose a getter, no setter. If we wanted a getter and a setter we would instead use var like this.

We can also control the access modifiers directly in the constructor as follows:

class Person(val firstName: String, private var lastName: String) {

}

Which now causes a problem is we try and use the lastname field outside of the Person class

image

Secondary Constructors

As in .NET, it is possible to have multiple constructors. However the rule in Scala is that any NON primary constructor MUST ALWAYS call the primary constructor

Here is an example using our simple Person class, which has a secondary constructor

//Primary constructor
class Person(var firstName: String, var lastName: String) {

  //secondary constructor
  def this(firstName: String) {
    this(firstName, "")
  }

  override def toString: String = {
    return s"firstname: $firstName, lastname: $lastName"
  }

}

Which we may use like this

object ClassesDemo {
  def main(args: Array[String]) =
  {

    val person1 = new Person("sacha","barber")
    val person2 = new Person("ryan")



    System.out.print(s"Person1 is $person1\r\n")
    System.out.print(s"Person2 is $person2\r\n")

    System.in.read()

    ()
  }

}

So that talks about how you might wrote constructors

Get/Set

Another thing we may want to add to our classes (outside of constructors) is properties. Here is our (by now famous) person class, rewritten to include a separate age property

//Primary constructor
class Person(var firstName: String, var lastName: String) {

  // Private age variable, renamed to _age 
  private var _age = 0
  var name = ""

  // Getter 
  def age = _age

  // Setter 
  def age_= (value:Int):Unit = _age = value




  override def toString: String = {
    return s"firstname: $firstName, lastname: $lastName, age: $age"
  }

}

Which we can use as follows:

 

Wait a minute aren’t we meant to be calling a method when we use the age setter?  In Scala, parentheses are usually optional. The age setter line could just as easily been written as

person1.age =(99)  
// OR 
person1.age_=(99)  

Tooling Compatability

Scala is a JVM language but is it not Java, and as such sometimes you may need to do a bit more work if you want to interop with Java correctly. Bean properties may be one area where extra work is required.

The reason for this is that in Java Beans there is an expectation that there are methods call getXXX() and setXXX().

Mmm curious. Luckily in Scala this is easy to fix, we just need to use a simple BeanProperty annotation

//Primary constructor
class Person(var firstName: String, var lastName: String) {

  @scala.beans.BeanProperty
  var age = 0




  override def toString: String = {
    return s"firstname: $firstName, lastname: $lastName, age: $age"
  }

}

Which you may then use like this:

val person1 = new Person("sacha","barber")
person1.age = 12
var theirAge = person1.getAge()

Note you may also do this on the constructor which may help should you wish to expose constructor parameters as bean properties

class Person(
              @scala.beans.BeanProperty
              var firstName: String,
              @scala.beans.BeanProperty
              var lastName: String) {

}

Methods

Methods in Scala are simply defined as follows

def ReverseAString(inputString:String) : String = {
    return inputString.reverse
  }

Where we specify that it is a method using the def keyword, and then a name for the method, and then any parameters followed by a colon and then a return type, then we supply the method body

We can then call this method like this (assumes we added this method to our Person class)

val person1 = new Person("sacha","barber")
val reversed = person1.ReverseAString("The cat sat here")

 

Static Classes / Static Methods

This is certainly one area where Scala and .NET differ. In Scala static methods go into a companion object for the type.

I actually think the Scala way makes a lot more sense, when you think about. The Person “OBJECT” has this method. Anyway here is a small example

//Companion object where Static things live
object Person
{
  def StaticDoubleIntMethodOnPersonType(input : Int) : Int = {
    return input * 2
  }
}


//Primary constructor
class Person(var firstName: String, var lastName: String) {

  override def toString: String = {
    return s"firstname: $firstName, lastname: $lastName"
  }

}

Which you could use like this

val doubled = Person.StaticDoubleIntMethodOnPersonType(10)

Scala

SCAla loops

 

This time we will look at how you can use the various loops within Scala

 

For Loops

The for loop in Scala is quite handy, and does some things that other languages do not provide within their for loop symantics

Range

The simplest for of a for loop is as shown here

//simple range for loop
var a = 0
for(a <- 1 to 10) {
    println(s"Value of a = $a")
}

Which would give the following results

image

You can also use until instead of to, which would give you the same results

Collections

You can also use a for loop to loop through a collection

//simple for loop through a collection
var list = List(1,2,3,4)
var a = 0
for(a <- list) {
  println(s"Value of a = $a")
}

Which would give the following results

image

 

Using Filters

Filters may also be applied to for loops, here is an example

//simple for loop through a collection
//with a filter for only even numbers
var list = List(1,2,3,4)
var a = 0
for(a <- list if a % 2 ==0) {
  println(s"Value of a = $a")
}

Which when run gives the following results

image

Using Yield

You can also create to new sequences (if you are a .NET programmer which is really who this posts are aimed at, this would be the same as using a LINQ Select to create a new IEnumerable for some source IEnumerable)

//simple for loop through a collection
//with a filter for only even numbers
//which use yield to create filtered sequence
var list = List(1,2,3,4)
var a = 0
var evens = for {a <- list if a % 2 ==0
            } yield a

for(a <- evens) {
  println(s"Value of a = $a")
}

Which when run produces the following results

image

 

While Loops

Much the same as other languages, Scala has a while loop that allows us to continue looping while waiting for a certain condition to be met. It is important to note that the while loop checks the condition at the top of the loop, so if the condition is already met the while loop may never run

//simple while loop
var a = 0
while(a < 10) {
  println(s"Value of a = $a")
  a = a + 1
}

Which when run will give the following result

image

 

Do While Loops

Scala also has the popular do-while loop, which unlike the while loop will check the condition at the end of the do-while, so is guaranteed to run at least once. Here is a simple example

//simple do-while loop
var a = 0
do {
  println(s"Value of a = $a")
  a = a + 1
}while(a < 10)
//import control packages to give us Breaks
import scala.util.control._

//simple breakable for loop
val loop = new Breaks()
var a = 0
loop.breakable {
  for(a <- 0 to 20) {
    println(s"Value of a = $a")
    if(a > 5)
      loop.break()
  }
}
println("Outisde the loop")

Which when run will give you the following results

image

 

Breaking Out Of Loops

This is one key area where Scala is very different from .NET. There is no built in break statement available.

However if you are using a version of Scala after 2.8 then there is a way to use a break statement inside your loops.

You need to import a package to allow this to happen.

The idea is that you wrap your loop in a breakable which is available by using the Breaks class. And then inside your loop when some condition occurs your may use Breaks classes break() method

Lets see an example

//import control packages to give us Breaks
import scala.util.control._

//simple breakable for loop
val loop = new Breaks()
var a = 0
loop.breakable {
  for(a <- 0 to 20) {
    println(s"Value of a = $a")
    if(a > 5)
      loop.break()
  }
}
println("Outisde the loop")

Which when run gives the following results

image

Scala

Scala types / variables

Since Scala is a JVM language it is not suprising to see that it has the same data types as Java.

The following table illustrates the common data types

Data Type Description
Byte 8 bit signed value. Range from -128 to 127
Short 16 bit signed value. Range -32768 to 32767
Int 32 bit signed value. Range -2147483648 to 2147483647
Long 64 bit signed value. -9223372036854775808 to 9223372036854775807
Float 32 bit IEEE 754 single-precision float
Double 64 bit IEEE 754 double-precision float
Char 16 bit unsigned Unicode character. Range from U+0000 to U+FFFF
String A sequence of Chars
Boolean Either the literal true or the literal false
Unit Corresponds to no value
Null null or empty reference
Nothing The subtype of every other type; includes no values
Any The supertype of any type; any object is of type Any
AnyRef The supertype of any reference type

The items in this table ara all objects, which means you can call methods on them.

For example suppose we has declared an int value like this:

var _int = 23

We could then call methods on it like this:

image

This is somewhat different to Java where there are true primitives. Scalas approach uses objects known as RichXXX which have something called implicit coversions, which allows them to be used to interop with Java where you may need to pass a Java primitive (say as int)

For example there is a RichInt class in Scala, which you can read about here

http://www.scala-lang.org/api/current/scala/runtime/RichInt.html

There are quite a few RichXXX classes in Scala, I would urge you all to read about them.

There is a good discussion on this at StackOverflow:

http://stackoverflow.com/questions/29655076/why-are-there-richint-or-richx-in-scala

For now lets see how we can declare some variables in Scala

Integers

Here are some valid ways to create integers

val _int1 = 0
val _int2 = 35
val _int3 = 21
val _int4 = 0xFFFFFFFF
val _int5:Long = 0XCAFEBABE

Floating Points

Here are some valid ways to create floating points

val _float1 = 0.0
val_float2 = 1e40f
val _float3 = 2.1543f
val _float4 = 6.0e600
val _float5 = .4

Booleans

Here are some valid ways to create booleans

val _bool1 = false
val _bool2 : Boolean = true
val _bool = _bool1 && _bool2

Characters

Here are some valid ways to create characters

val _char1 = 'b'
val _char2 = '\u0037'
val _char3 = '\n'
val _char4:Char = '\t'

Strings

Here are some valid ways to create strings

val _string1 = "Hello,\nWorld!"
val _string2 = "This string contains a \" character."

Multiline strings

You can also create multiline strings like this

val _multiLineString ="""this string
                          is a long one, it has 
                          3 lines."""

String interpolation

Scala also support string interpolation, such that you can do things like this

val _string1 = "Hello,\nWorld!"
val _string2 = "This string contains a \" character."
val string3 = s"The value of string1 = $_string1, and string2 = $_string2"

Escape Sequences

The following escape sequences are valid

Escape Sequence Unicode Description
\b \u0008 backspace BS
\t \u0009 horizontal tab HT
\n \u000c formfeed FF
\f \u000c formfeed FF
\r \u000d carriage return CR
\” \u0022 double quote “
\’ \u0027 single quote .
\\ \u005c backslash \

 

Var vs Val

There is one last thing I wanted to mention in this post, which is the difference between var and val in Scala.

Val

Basically val is an immuatble object. That is you can change the value of it, but you will not be able to recreate a new object pointer (reference) for a val. This would be an error. A object assigned to a var can still have its internal state altered though.

Var

Var on the other hand is mutable , and as such will let you assign a new object pointer (reference).

There is a great StackOverflow post on this, which I would encourage you all to read:

http://stackoverflow.com/questions/1791408/what-is-the-difference-between-a-var-and-val-definition-in-scala

Scala

SBT : Where’s my NUGET

 

This article assumed you have done the other stuff in getting the tools to create SCALA projects

SBT stands for Scala Build Tool, This tool is kind of equivalent of Nuget in .NET, you can use SBT to download dependencies and also to compile your own code into JAR files, much the same way you would have with Nuget,exe where you would have created .nupkg for .NET projects.

Going through every feature of SBT is slightly out of scope  for this post, however I will go through some of the common things you may want to do with SBT.

For the full walk through you should check out these 2 links

Like I say, I will not be able to cover everyting that SBT does, It is after all a complete build system.

So let’s concentrate on a few things that are common place when using some sort of package management / build system.

 

How Do I Build My Own Scala Code To A JAR

So when you create a new SBT project in IntelliJ (my chosen) IDE.

Lets say I had created a new project in IntelliJ that looked like this:

 You will get a default SBT file that looks like this

name := "SBTDemo"

version := "1.0"

scalaVersion := "2.11.7"
    

This simply specifies the name of the

image 

Where I have a Scala class like this

object SBTDemo {
  def main(args: Array[String]) =
    {
      println("Hi!")
      System.in.read()
      ()
    }

}

We can create a new JAR for this using the following procedure:

  1. Open a command prompt where you created the scala project
  2. Check that folder is the one with the built.sbt folder in
  3. Type SBT in command line window
  4. This will give you a SBT context, and then you should be able to enter SBT command directly
    • So we should be able to type “SBT package”, which should package the current project into a JAR file. For me this was this simple TEST project that created the following JAR file

image

You may be thinking great so now I have a JAR can SBT run it. Well no you would tend to run the actual JAR through Java or Scala command line. Here is an example Scala command line to run the example JAR file produced by this simple SBT example

image

How Do I Get Dependencies

Another really common thing to want to do is to reference external dependencies. These dependencies are just like Nuget packages in .NET, they are hosted on the web there is a package repository, and they may be brought down into the project using SBT.

These dependencies are all mainly available from the Maven Central Repository or mvnrepository.com if you prefer that

Once you have found what you would like to reference you can update you SBT file.

For example suppose you wanted to use RabbitMQ, we would update our SBT file to look like this

name := "SBTDemo"

version := "1.0"

scalaVersion := "2.11.7"

libraryDependencies += "com.rabbitmq" % "amqp-client" % "3.5.6"

If you are using a IDE, the IDE will probably download the dependencies for you, you can however use a SBT command line, and issue the SBT command “update”.

SBT will bring all 3rd party JARS down to your IVY2 folder which should be something like

C:\Users\sacha\.ivy2\cache

 

Building Your Own Code As A Shared JAR

Imagine you have some shared code and you want different projects to reference this as a dependency (think project reference, or Dll in .NET).

We now know we can use SBT to resolve 3rd party dependencies, but how about our own code. How does that get into the IVY2 cache folder. This is the job of SBT PublishLocal

Here is a good guide on how to do that:

http://www.scala-sbt.org/0.12.4/docs/Detailed-Topics/Publishing.html#publishing-locally

 

Scala

Getting the tools to create a Scala Project

 

This post is going to be a pretty small one that talks you through one possible way of getting all you need to start experimenting with Scala.

There are obviously other ways, but this is the toolset I personally have found to be quite useful.

So what are the bits and bobs you need to get working with Scala. Well there are really only 2 things you absolutely must have, these are

Java

You MUST have a version of java installed. I would recommend the latest version which you can grab from this site :

http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

Obviously grab the one that suits your requirements

Scala

You will also need Scala, I would recommend you use the latest version of that too. You can grab that from this site:

http://www.scala-lang.org/download/

That is actually strictly all you need to create a Scala program, but we have all probably come from places where we use an Integrated Development Environment (IDE), so let’s grab on of those too.

SBT

However just before we grab the IDE, let’s make our lives easier and grab a copy of SBT (a nice build tool). You can grab this from this page:

http://www.scala-sbt.org/download.html

We will make use of SBT in future posts, but for now we just want to make sure we have downloaded a copy of it

IntelliJ

There are numerous IDEs out there, I happen to like IntelliJ as it comes with a nice free community edition and is a fairly nice IDE (I still think its way behind Visual Studio though).

You can grab IntelliJ from here:

https://www.jetbrains.com/idea/download/

 

With all that in place you should now be able to create a new project in IntelliJ which should target Scala + SBT

Something like this

image

image

image

On this screen I would recommend that you tick the box “Use Auto Import”, which allows SBT to auto import packages you have requested.

After you have finished this wizard, SBT will do a bit of work, this will take a little while even for a brand new project. Let it do its magic (you will need internet connection), and then you should be left with a project structure something like this:

image

You would then place code in the Scala folder that matches the version you chose to target. For example for this project I chose to use Scala 2.11, so that is what folder I would add my new Scala code files too in the the IntelliJ project.

Anyway that is all I wanted to say for now. We will continue our journey in subsequent posts.