Tutorials Hut

Tutorials Hut




  • Scala Basic Syntax: Object, Class, Closure and More

    In this we will understand Scala Basic syntax, Object, class and much more. Scala is similar to Java or C++ in terms of having classes and objects, It has a lot of classes and objects and a lot of functions and functional concepts to write any logic in Scala.

    Scala uses a lot of functions, functions can be used as variables, can be returned from a function and can be passed as an argument of function that is why Scala is called functional programming language.

    If you have previously worked on Java or C++ or similar OOP languages then below concepts of Scala will be easy to understand.

    scala

    1) Class: Class is a blueprint or skeleton of a real life object. Classes have attributes and functions defined within then and logic. For example a Tree class can be skeleton or blue print of real life object Tree in Scala.

    Example:

    class Tree {
    }

    2) Object: Object is an instance of a class for example tree1 can be an object or instance of a Tree class, from a class we can any number of objects we want. Usually we use new keyword along with Name of class to create objects.

    Example:

    class Tree {
    val tree1 = new Tree() //Object of Tree
    }

    3) Functions or methods: Functions or methods are behaviour of a class, for example if we create giveOxygen() function in a Tree class and write some logic in it then it will show behaviour of Tree class and this is called function or method in Scala.

    Example:

    class Tree {
    val noOfBranches = 20
    def giveOxygen() = { //Function
    }
    }

    4) Fields/Variables: Fields or variables hold values of class attributes for example a Tree class may have to hold how many branches are in tree and so we can have a variable named noOfBranches which cana hold totoal number of branches in Tree.

    Example:

    class Tree {
    val noOfBranches = 20 // Variable
    def giveOxygen() = { //Function
    }
    }

    5) Closure: Closure is a function which is written differently than normal functions and may depend on outside variables values. Its definition is anonymous.

    Example:
    val doubleValue = (i: Int) => i*2

    6) Traits: Traits are similar to interfaces which may have unimplemented methods and any class other class may implement traits and will need to implement the functions of traits as well. They provide abstraction in Scala.

    Example:

    trait MyTrain {
    def readData()
    def writeData()
    def doSomething()
    }

    7) Generics: Scala has generics similar to Java where we can define a generic data type and later use it based on our requirement.

    Example:
    In this example we have a class named MyDataClass which has a generic data type T while creating an actual class by using this we can have T of any type Int, Float or String.

    class MyDataClass[T] {
    private var amount: T = _
    def set(value: T) { amount = value }
    def get: T = amount
    }

    Below example code is using above generics with type Int data:

    object MyIntDataClass {
    def main(args: Array[String]): Unit = {
    val myDataClass = new MyDataClass [Int]
    myDataClass.set(13)
    println("Reference contains the half of " + (myDataClass.get * 2))
    }
    }

    Simple Scala Program Using Console Interactive

    If you already have installed Scala in your MAC or Windows machine can simply open console (CMD in windows) and type “scala” command and hit enter, this will take you to Scala console where you can write basic Scala syntax and practice.

    Let’s do a step by step example:

    Step 1: Open console and type scala.

    ➜ ~ scala
    Welcome to Scala 2.12.8 (OpenJDK 64-Bit Server VM, Java 1.8.0_222).
    Type in expressions for evaluation. Or try :help.

    scala>

    Step 2: Write any Scala valid syntax, for example println(“Hello Scala”)

    scala> println(“Hello Scala”)
    Hello Scala

    You can see we write println(..) and it printed the word on console, this is a simple example of console mode of Scala to write and practice Scala code.

    First Simple Scala program with Class

    Follow below steps to write a simple Scala program

    Step 1: Open and notepad or any text editor and write below code and save as SampleProgram.scala.

    object SampleProgram {
    def main(args: Array[String]): Unit = {
    println("Hello from sample scala program")
    }
    }

    Step 2: Open console (CMD in windows) and go to path where SampleProgram.scala is saved and type below command to compile it and next just run scala command with class name to execute it, shown in below:

    ➜ scala scalac SampleProgram.scala
    ➜ scala scala SampleProgram
    Hello from sample scala program

    You can see the output “Hello from sample Scala program” is printed.

    Congratulations, you have completed your first sample Scala program.

    Basic Syntax

    Please note below points while writing any Scala program:

    1) Case sensitivity: Scala is a case sensitive programming language that means any reserved key words or variable or method or class name case can’t be changed from lower to upper or upper to lower case, for example – if have declared a class with name “Tree”, you can’t refer it with “tree” or “tRee” this may give error.
    2) Class names: Class name’s first letter should be capital, if class name has many words each word’s first letter should be in capital letter; you may choose to differ but it is wrong practice.
    Few examples of good class names:
    Tree
    Planet
    School
    Account
    SavingAccount
    FixedDepositAccount

    Few examples of bad class names:
    tree
    planet
    SchooL
    savingAccount
    Fixeddepostaccount

    3) Method and Variable Names: Method or function name in Scala should always start with small letters and if it contains more than one word then first letter of each word should be capital letter.

    Few examples of good method names in a Tree class:
    giveOxyzen()
    absorbCarbondioxide()
    doPhotoSynthesis()

    Few examples of bad method names in a Tree class:

    GiveOxyzen()
    Absorbcarbondioxide()

    Variables name should also be similar to method names.

    4) Scala program file name: File name should same as class name and should follow the same naming conventions as class name, you may choose to differ but is wrong and will have issues in future programming.
    Please note that file should be saved with extension “.scala” only.

    Few examples of good file names:
    Tree.scala
    Planet.scala
    School.scala
    Account.scala
    SavingAccount.scala
    FixedDepositAccount.scala

    Few examples of bad class names:

    Tree.scala
    Planet.scala
    SchooL.scala
    savingAccount.scala
    Fixeddepostaccount.scala

    5) main() method: In Scala if you want to start a program the class loaders will look for main method first and then start execution from there, so main method is the entry point in standard Scala program.

    See below syntax of main method in any Scala class:

    def main(args: Array[String])

    Scala Identifiers

    All Scala program components need name. Names of class, variables, methods and objects are called identifiers in Scala.

    We can categorize them in 4 below types:

    • Alphanumeric Identifiers:
      Using alphabets and numbers if we write name of variable or methods will be called alphanumeric identifiers. Below are few examples:

    amount, amount1, amount_1 etc.

    • Operator Identifiers:
      Some reserved keywords used in Scala while doing operations are called operator identifiers.
      Examples of operator identifiers:
      + ++ ::: <?> :>
    • Mixed Identifiers
      Mix of alphanumeric and operator identifiers is called mixed identifier.
      Examples:

    Amount_+, mydata_=

    • Literal Identifiers:
      A literal identifier is a string enclosed in back ticks (`String dat`) Examples:

    `tutorials`
    `John`
    `Matrix`

    Scala Keywords

    Below are reserved Scala keywords and should never be used as literals:

    truetypevalVar
    superthrowtraitTry
    protectedreturnsealedsuper
    objectoverridepackageprivate
    lazymatchnewNull
    forSomeifimplicitimport
    false
    finalfinallyfor
    defdoelseextends
    abstractcasecatchclass
    <-<:<%>:
    :==>
    whilewithyield@
    #

    Comments in Scala Program

    You may choose to add comments in the Scala program for providing some details about a class or a method but always remember that comments are never executed in Scala.

    Adding comments is a very good practice in writing real world Scala program.

    There are two ways to write comments in any Scala program, let’s have a look:

    1. By using two forward slash (// comment) This can be used if you want to add single line comments.
    2. By using forward slash with star (/* comment */) This can be used if you want to write multiline comment in your Scala program.

    See below example of both:
    Just below class Tree there is multiline comment and then after main method there is a single line comment.

    class Tree {
       /* This is my first Scala program the name of class is Tree.
    	* This is an example of multiline comment
    	*/
    	def main(args: Array[String]): Unit = {
       	// This is an example of single line comment
        	println("Hello, I am a tree");
    	}
    }

    Reference:

    Scala reference from Scala org: Scala Basic

    Next Article to Read:

    • Scala Class and Objects.

















  • Leave a Reply

    Your email address will not be published. Required fields are marked *

    Scroll to Top