Wednesday, 12 August 2020

Scala: Mutable and Immutable variables

Variables in Scala are defined using either by the keyword ‘var’ or ‘val’. ‘val’ is equivalent to the final keyword in Java.

‘var’ is used to create mutable variables, whereas ‘val’ is used to create immutable variables.

 

Declaring a mutable variable

Syntax

var variable_name : Data_Type = value

 

Example

var principle : Integer = 100

scala> var principle : Integer = 100
var principle: Integer = 100

scala> principle = 123
// mutated principle

scala> print(principle)
123
scala> 

scala> principle = 555
// mutated principle

scala> print(principle)
555

Declaring an immutable variable

Syntax

val VARIBALE_NAME : Data_Type = value

 

Example

val PI : Double = 3.14

scala> val PI : Double = 3.14
val PI: Double = 3.14

scala> print(PI)
3.14

When you try to assign some value to this immutable variable PI, you will get an error.

scala> PI = 3.1428
          ^
       error: reassignment to val

Scala can infer the type from the value

Specifying type is optional, scala infers the type using the value assigned to the variable.

 

var name = "Krishna"

 

For example, from the above statement, Scala can infer the type of variable name as String.

scala> var a = 10
var a: Int = 10

scala> var name = "Krishna"
var name: String = Krishna

scala> var flag = true
var flag: Boolean = true




Previous                                                    Next                                                    Home

Sunday, 9 August 2020

Scala: Eclipse: Hello World using worksheet

 Install Scala IDE in Eclipse

Open Eclipse. Help -> Eclipse Market Place…

 

Search for Scala IDE.

Click on Install button under Scala IDE 4.7.X.

Use default selection and click on Confirm button.

 

Once the installation is successful, restart Eclipse.

 

Create a new scala project

Open Eclipse. File -> New -> Other.

Select Scala Project and click on Next button.

Give the project name as ‘hello-scala’ and click on the Finish button.

 

Scala project structure looks like below.



Create new worksheet

Open Eclipse. File -> New -> Other.


Search for scala and select ‘Scala Worksheet’, click on Next button.


Select the project ‘hello-scala’ and give the worksheet name as ‘helloworld’ and click on Finish button.

helloworld.sc worksheet created with the above content. Now whatever you experiment on worksheet, statements are immediately get executed once you save the worksheet and you can see the result in the same worksheet.


Previous                                                    Next                                                    Home

Scala: Hello World using scalac and scala

 In my previous post, I explained how to develop and run a hello world application in Intellij IDEA. In this post, I am going to explain how to develop, compile the application using a scala compiler (scalac) and run the application using ‘scala’ command.

Step 1: Create HelloWorld.scala file.

 

HelloWorld.scala
/*
Below snippet creates Singleton Object
*/
object HelloWorld{

	def main(args: Array[String]): Unit =  {
		print("Hello World")
	}
}

Step 2: Compile HelloWorld.scala file by executing below command.

scalac HelloWorld.scala

$scalac HelloWorld.scala 
$
$ls
HelloWorld$.class	HelloWorld.class	HelloWorld.scala

Compilation generates .class file.

 

Step 3: Execute HelloWorld application by executing the below command.

scala HelloWorld

$scala HelloWorld
Hello World

Let’s decompile HelloWorld.class and see how the generated java code looks like.

 

Explanation

object HelloWorld

‘object’ keyword is used to create singleton object. Right now, you just understand that, main method is the entry point to the Scala application, you should keep main method in singleton object defined using ‘object’ keyword. I will explain more details of object keyword later.

  

HelloWorld$.class decompiled code looks like below.

import scala.Predef$;

public final class HelloWorld$ {
  public static final HelloWorld$ MODULE$ = new HelloWorld$();
  
  public void main(String[] args) {
    Predef$.MODULE$.print("Hello World");
  }
}

HelloWorld.class decompiled code looks like below.

import scala.reflect.ScalaSignature;

public final class HelloWorld {
  public static void main(String[] paramArrayOfString) {
    HelloWorld$.MODULE$.main(paramArrayOfString);
  }
}



Previous                                                    Next                                                    Home

Scala Hello World in Intellij IDEA

 Step 1: Open IntelliJ IDEA.

Step 2: Intellij IDEA -> Preferences…


Step 3: Select Plugins. Search for scala plugin.


Select Scala plugin and click on Install button. Intellij will start downloading the plugin. Once the plugin is downloaded successfully, Intellij install Scala plugin.

 

Once the Scala pluing is installaed successfully, you will be asked to restart Intellij IDEA.


Click on ‘Restart IDE’ button to restart IDE.

 

Step 4: Once IDE is restarted, you will see below kind of window.



Click on ‘Create New Project’.

Click on Scala menu and select Lightbend Project Starter.

Click on Next button.


Give the project name as ‘helloworld’ and select the seed project as ‘Hello, Scala!’.

 

Click on Finish button.

 

Project structure created like below.


Open Hello.scala file, you will see below snippet.

 

Hello.scala

package example

object Hello extends Greeting with App {
  println(greeting)
}

trait Greeting {
  lazy val greeting: String = "hello"
}

Run the application Hello.


You will see the message hello in the console.

 

That’s it you are done……:)




Previous                                                    Next                                                    Home

Installing Scala

 Prerequisite

Install JDK in your system.

 

Step 1: Go to below location and download scala binaries.

https://www.scala-lang.org/download/ (or) https://github.com/lampepfl/dotty/releases


 

Step 2: Extract the downloaded binaries in step1.

 

Step 3: Set the variable SCALA_HOME to the path where Scala is extracted.

 

Set Scala bin directory path to your system path. Open new terminal and execute below command.

 

export PATH=$PATH:$SCALA_HOME/bin

 

Step 4: Execute the command ‘scala’. It opens scala REPL (Read-Evaluate-Print-Loop) prompt.

$scala
Welcome to Scala 2.13.3 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_251).
Type in expressions for evaluation. Or try :help.

scala>

You can evaluate expressions at scala REPL prompt.

scala> 1 + 2
val res0: Int = 3

scala> 20 + 30
val res1: Int = 50

Similarly you can print data to console using the print function.

scala> print("Hello World")
Hello World 

Execute the command :quit to come out of scala REPL prompt.



Previous                                                    Next                                                    Home

Introduction to Scala

 Scala is a general-purpose programming language like Java. Scala was developed to solve the shortcomings of Java Programming language. Distributed computing frameworks like Apache Spark uses Scala widely. 

Scala is syntactically concise, it infers the type, semicolon depends on the context.

 

Scala uses both a compiler and interpreter. For example, you can create Scala scripts that are interpreted. If you compile the Scala code, it is converted into Java byte code. Scala compiler also compiles the code to JavaScript.

 

Is Scala an Object-Oriented Language?

Yes, Scala is a pure object-oriented programming language. Since Scala is a pure object-oriented language, functions are also objects.

 

Scala also supports functional constructs like pattern matching, closures, and Currying.

 

Is Scala supports Operator overloading?

Yes, Scala supports operator loading. Scala treats operators as methods of an object.

 

Is Scala statically typed?

Yes, Scala is a statically typed language. Variable type must be known at compile time. That means once a variable is declared with type ‘T’, you can’t change the type of variable in its lifetime.

 

Scala runs on JVM

Since Scala runs on Java Virtual Machine, you can use all the existing Java libraries in Scala.

 

Scala does not have primitive types

There are no primitive types in Scala. Everything is an object.


Previous                                                    Next                                                    Home

Saturday, 8 August 2020

Scala Tutorial


      Introduction to Scala
      Installing Scala
      Scala Hello World in Intellij IDEA
      Hello World using scalac and scala
      Eclipse: Hello World using worksheet
      Mutable and Immutable variables
      semicolons are optional
      Data types
      Working with Strings
      Define a string
      Concatenate strings
      Triple quotes to handle multi line strings
      String interpolations
      Formatting strings: printf notation
      Unified Type System
      Type Operators
      Expression and statements
      Expression Blocks
      Nested Expression Blocks
      if/else expression blocks
      What if condition returns value of some type and else return some other type
      match expression
      How to handle Scala.MatchError
      Match expression: Test the type of a variable
      for loop
      for loop as expression
      for loop with if condition
      Nested for loops
      for loop works for any collection
      while loop
      do-while loop
      Lambda Expressions
      Functions
      Named Parameters
      Default values to arguments
      Varargs: Variable number of arguments
      Arrays
      Traverse an array
      ArrayBuffer
      Maps
      Iterate over a map
      Convert a map of (key, value) to map of (value, key)
      Tuple
      Classes
      How to define a constructor?
      Infix notation of methods
      How to define static methods and singletons
      Companion Object
      Statements in the class body gets executed while initializing an instance
      Hello World project in Eclipse
      Packages
      Inheritance
      Traits
      Emptiness
      Operators are methods
      functions
      Currying
      Create java.lang.Object instance
      to method
      Working with BigInt
      Method without parameters do not require () while calling
      apply method can be called without name
      Get square root of numbers from 1 to 10
      Get permutations of a string
      Convert integer to character
      Convert character to integer
Previous                                                    Next                                                    Home