Learn

Learn about latest technology

Build

Unleash your talent and coding!

Share

Let more people use it to improve!
 

scala in a nutshell

martes, 7 de marzo de 2017

We will start this post with Scala, won't say the advantages it has, Ordesky has done it and I won't say the advantages of a functional language, you can find it doing googling.
The Scala installation is here, it's the language site. From here you can download and follow the installation instructions. However if you want to install it on a linux I have a script in my github, which has been installed in both a Centos and OSX, as an important detail change the version that the script points to, in my case I have it for the 2.11.2. An important detail, Scala uses the java VM so that before doing the installation or trying to invoke the Scala console make sure you have installed java before.

Some tips before begin:
A construction tool strictly necessary to work with Scala is sbt, it has its own console and as any construction tool allows compiling code and also allows us to select available projects, run test suites on them or some particular test unit. It is definitely a very useful tool and we will certainly spend time with it in the future. If you want to start looking I encourage you go to the site of sbt and download it.

Regarding code editors / ides to use, for small pieces of code you can use the console even in times of structuring project, when coding I use Sublime Text but for projects of a certain magnitude I recognise that Eclipse or IntelliJ will be better. Other Option for the lovers of the cloud can be this ide (http://c9.io), is one of the best ides that I have seen in the cloud, it also has a git repository and a linux, ubuntu embedded. We can compile, execute and everything that we normally do with in an integrated development environment (IDE).

I think after this brief introduction we can begin. Our goal today is to explain some Scala syntaxs in the shortest possible way so that someone coming from the Java world can understand easily.


The simple way for define a function in Scala, this is the equivalent of a function in java. It is like void(in java) don't have return value:

1
2
3
4
5
6
7
//defining a basic function
//x, y are Int input parameters
//function returns an Int value type           

def max(x: Int, y: Int): Int = {
   if (x > y) x 
      else y }

The above structure is the basic structure of any function with the reserved word def.

It is important to consider that functional programming leaves a lot of things assumed and its solution is carried out in the background by JVM.

We have an example that can be solved in different ways. An array of String, with 3 elements and we will print them in the console:

1
2
3
4
//define the array and initialize it 
val args = Array("one","two","three")
args.foreach(arg=>println(arg))
args.foreach(println) 

In line 3, we print the contents of the array, in just one line. With foreach we go through all the elements of the collection and arg => println(arg) is a function that takes a parameter and returns as a result something that does with that parameter (println (arg)). This operator (=>) is a syntactic sugar.
In the case of line 4 we simply print all the elements of the array, without being able to interact with them.
(=>) As we indicated earlier this is one of our main operators in Scala whereby it is really important for us to leave summarized all its functionality.

val f: Function1[Int,String] = myInt => "my Int value: " + myInt.toString

Here is a function that receives an integer (Int) and returns the string "my value int": + parameter value entered. The above is a function definition launched from console.

val f1: Int => String = myInt => "my other Int value: " + myInt.toString

Functionality and result of both f and f1 is the same. Look at how the function f1 is translated, we have a function f1 that receives an integer (Int) and returns a String, with the value received as parameter, myInt, I will do  (=>) what I have to do and in my case it is print a string of text with the value of the integer.

() => Unit
val f : () => Unit  = () => println("Hello world") 
val f : () => Unit  = () => {//any operation in the same line must be separted by ;}  
val f : () => Unit  = () => {//any operation in different lines is not necessary (;) }

Thats functions neither receive parameters nor return any value, like a void in java language, does not return values.

An equivalent definition whose result would be the same as the rest of the previous group is the following line of code:

val f2: function0[Unit] = () => println("any value")

Let's see another utility of this fantastic operator:

List(1,2,3).map { (x: Int) => x * 2 }

We have a list and we want to multiply its elements * 2. That is what our previous line of code does. Let's forget the map functionality for a moment, which is not complicated and can be found at Scala Api doc without any problem to be understood.
The line of code: (x: Int) => x * 2 indicates that we are going to take each integer Int that is passed as a parameter and will doubled.

(_) underscore: this is an operator of great importance and has, in Scala, a myriad of utilities that we will explain below:

1
2
3
4
5
6
7
val miArgumento = "salt"
        firstArg match {
          case "salt" => println("pepper")
          case "chips" => println("salsa")
          case "eggs" => println("bacon")
          case _ => println("huh?")
}

In the previous case, line 6 is executed by default, when aforementioned conditions are not fulfilled.
We also use it(_) in the imports in what could be the * in the case of imports in Java:

import scala.util.control.Breaks._
import java.io._

Perhaps its most important use is as a placeholder. Let's introduce the following example to see more clearly its functionality:

1
(x: Int) => x > 0

If we apply what we saw previously for operator => , line 1 indicates that the function receives an Int value and returns a boolean value, this boolean value  will be true when the input parameter is > 0. Suppose we have the following list of values:

val values = List(-21, -11, -3, 0, 15, 20)

An important detail to bear in mind: internally when we create a list (List) or an array (Array) we actually invoke the following method: Array.apply, for those who come from the java world we could talk of this method as a static method in Java (saving distances, since in Scala we do not have neither variables nor static methods). Here is an example about creating a list.

//code example with apply
val values1 = List.apply(-21, -11, -3, 0, 15, 20)

As we can appreciate, the way of creating a collection initialized is simpler as it appears in the creation of the list without invoke directly to the apply method(note that internally will invoke this method always).

Later we will try the collections, right now we just need to know that List has a method to filter the elements of it(filter), so if we wanted to filter the elements of that list and leave in it only those elements > 0 the syntax should be the following:

values.filter((x: Int) => x > 0)

The previous line of code filters all the elements of the list and leaves in it the items> 0. In reference about the filtering condition see the explanation in previous lines.

The previous line of code is success if know the type of elements that the list contain. We will do the same using placeholder(_) , then let's see how our line of code is:

values.filter(_>0)

Another example could be a function that receives two parameters of a certain type, see the following line of code:

val f = (_: Int) + (_: Int)

The previous function will add 2 integers and is a solution that would be _ + _, a solution that would return an error due to an ambiguity in the parameters.
There are many cases where we would use the underscore (_) as a placeholder. Here is another example in the following line:

1
2
values.foreach(println _)
values.foreach(arg => println(arg))

Both solutions are valid, I lean for the line 1 that is a bit more compact and it is still intuitive. Remember that if we want to print only contents is enough with the following line:

values.foreach(println)

We will explain another use of (_) as placeholder

//create sum function  
def sum(a: Int, b: Int, c: Int) = a + b + c 
//set valueSum with the sum function, you do not need to declare 
//the variables due  to  you are using _ as placeholder
//will assume that you know the rest of params
val valueSum = sum _
//this operation is possible, return 11
valueSum(2,4,5)

When we assign the value  with sum _ the underscore  is necessary to indicate that we have more parameters, how many? those that have been defined in the function sum. We have here something curious, with the assignment we have an instance of an internal class of Scala, which will allow us to perform the following operation valueSum(2,4,5) or valueSum.apply(2,4,5). In the latter case we are calling a method that will assign the parameters for make a call to the function. We could say that with the assignments we have the instance of the inner class of Scala and with it, the apply method, for practical purposes we will not be using it either.

val otherValueSum = sum(1, _: Int, 3)

The above assignment is also valid. Here we see another utility in which the underscore acts as a placeholder and will execute the function only by calling a parameter eg otherValueSum.apply(4) or otherValueSum(4), both statements are valid.
Finally in this delivery we have the Clousures, which are? Conceptually are functions that contain what we call free variables, variables that do not depend on any parameter passed to the function. They are closed variables, variables that are not visible when you are creating the function. Let's see an example:

(x: Int) => x + freeVariable

In the previous code freeVariable does not depend on any input parameter and in this case will generate an error since it has not been declared. In the following example we see what are the free variables previously explained.

var freeVariable = 10
val addfreeVariable = (x: Int) => x + freeVariable
addfreeVariable(20)
res3: Int = 30

The function value addfreeVariable created in runtime is called Clousure (object function that contains free variables, which are not seen just when the function is being created).
A detail, freeVariable could change its value and still the value of the function would be updated for the new operations. Scala solve it internally without we have to worry about it.
The following example shows an array, we will pass a function to its foreach method, that function is a Clousure since it contains a free variable (which is not passed as a parameter):

var summation = 0
val aArray = Array(-3,5,7,9)
aArray.foreach(summation +=  _)

The summation variable is a free variable that uses underscore (_) as a placeholder and will add each of the array elements aArray. A simple detail that is extremely important is the use of var and val; the first declares a value that can be modified while the latter, val, declares a fixed value. If in the previous code we replaced line 1 with the declaration of val sum = 0, the code would generate error since in that case variable could not be modified.

We have seen the following operators: _ ; => and the clousures. Some of the examples contain theory that we have not seen yet, but for the moment the idea is focus on the previous operators and their different uses.
Well "people" until another delivery I wish them good luck and while I hope you will advance in Scala, our final target: build application with Scala. Till next entry ...

0 comentarios:

Publicar un comentario