Scala, the better Java

one stop site for scala learners

Local/Inner function in Scala

In Scala, we can define function inside function. In other words, inner/local function definition is allowed in Scala. The same concept is not possible in Java. In Java, you can define functions only at the class level. But, When it comes to defining function inside function, it is quite possible in Scala. Inner/local function is some way complements Functional programming in Scala.

Lets starts with simple demo snippets.

Lets define a Scala object called MyFactorial.scala. The code sample simply creates Singleton object names MyFactorial. I have defined main function as well so that we can simple call, MyFactorial.main(Array(0))

object MyFactorial {

  // main function
  def main(args: Array[String]) :Unit = {
    println("hello factorial!");
  }

}

Now, proceeding further, lets add factorial function called fact() which accepts an integer to calculate its corresponding factorial value.

 

See below code snippet which performs factorial of a given integer with the use of local/inner function named perform.

object MyFactorial {

// main function
def main(args: Array[String]) :Unit = {
  println("hello factorial!");
  val n = 5;

  // string interpolation
  val msg = s"The factorial of $n is ${fact(n)}.";
  println(msg);
}

 // method which calculates factorial
 def fact(n: Int):Int = {

 	// inner or local function
 	def perform(n:Int, result:Int):Int = {
 		if( n <= 0 ) {
 			return result;
 		} else {
 			return perform( n-1, n* result);
 		}
 	}

 // call to inner function
 return perform(n, 1);
 }

}

As you can see from the above code snippet that, function fact() has defined inner/local function, perform() to perform actual calculation on given number and return final result.

I am from Java programming background, as you can see, I have written fully expressed code snippet with all the curly braces in if-else statement, semicolon after every statement.

But in Scala, programming language, we can write very compact code as shown in below version of same piece of code snippet without

  • return keywords
  • curly braces for if-else statement
  • optional semicolons

 

object MyFactorial {

  // main function
  def main(args: Array[String]) :Unit = {
    println("hello factorial!")

    val n = 5

    // string interpolation
    val msg = s"The factorial of $n is ${fact(n)}."
    println(msg)
  }

  // method which calculates factorial
  def fact(n: Int):Int = {

    // inner or local function
    def perform(n:Int, result:Int):Int = {
      if( n <= 0 ) result
      else perform( n-1, n* result)
    }

  // call to inner function
  perform(n, 1)
  }

}

 

I am printing output message using another Scala feature related to String processing called String Interpolation as shown in above code snippet inside main() function.

The output is shown below,

 hello factorial! The factorial of 5 is 120. 

 

On contrary, we cannot use local/inner function in Java.

I hope you enjoyed this post.

Advertisements

The better object equality support in scala compared to java

Scala is considered to be better than Java in various aspects when it comes to ease of programming. But, there are some group of programmers who still like to debate on various aspects of Scala. Now, i am going to show examples on how easily we can do the object equality test in Scala compared to Java.

In Scala, everything is an object. We can use == operator to check for object equality. Have a look at the below code samples,

You can also try these samples by starting the scala REPL[Read, Evaluate, Print, Loop] prompt.

scala> 5 == 5
res0: Boolean = true
scala> 5 == 8
res1: Boolean = false
scala> 6 != 0
res2: Boolean = true

The comparisons shown above are samples of regular application. Let us see more on this.

We can apply the object equality across the types, such as

scala> 1 == 1.0
res3: Boolean = true
scala> 2 == 2.0001
res4: Boolean = false

You can observe from the above 2 comparison that, object equality can be done on two entirely different object types.

Now, the things become more and more interesting as we start learning more and more about object equality support in Scala language. Look at the below code samples on Lists. It’s quite good to have such support built into the language itself.

scala> List("Martin Odersky", "Jonas Boner") == List("James Gosling", "Patrick Naughton")
res5: Boolean = false scala> List(1,2) == List(1,2)
res6: Boolean = true

One last set of samples on null references handled during object equality. THIS IS QUITE INTERESTING TO KNOW. FOLLOW ME.

scala> null == List(2,3)
res7: Boolean = false scala> List(2,3) == null
res8: Boolean = false

You can compare against Null, and NO EXCEPTION IS THROWN.

The == operator is carefully designed such that we can use it for most of our daily use cases as shown above.

It is done with a simple rule. First check the left-side for null. If is it not null, then call “equals” method on it. The behavior of equals method is entirely depending on the type of the left-hand side argument.

Since, there is an automatic null check, you don't have to do it on your own!!!
 
To know more about current happenings in Scala world, please visit the official site of scala programming, http://www.scala-lang.org/.