Header Ads Widget

SCALA

SCALA: 

Introduction

Scala is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It seamlessly integrates features of object-oriented and functional languages.

Classes and Objects

A class is a blueprint for objects. Once you define a class, you can create objects from the class blueprint with the keyword new. Through the object, you can use all functionalities of the defined class.

Class

Following is a simple syntax to define a basic class in Scala. This class defines two variables x and y and a method: move, which does not return a value. Class variables are called, fields of the class and methods are called class methods.

The class name works as a class constructor which can take several parameters. The above code defines two constructor arguments, xc and yc; they are both visible in the whole body of the class.

Syntax

class Point(xc: Int, yc: Int) {
  var x: Int = xc
  var y: Int = yc

  def move(dx: Int, dy: Int) {
      x = x + dx
      y = y + dy
      println ("Point x location : " + x);
      println ("Point y location : " + y);
  }

you can create objects using a keyword new and then you can access class fields and methods

Extending a Class

You can extend a base Scala class and you can design an inherited class in the same way you do it in Java (use extends keyword), but there are two restrictions: method overriding requires the override keyword, and only the primary constructor can pass parameters to the base constructor.

Implicit Classes

Implicit classes allow implicit conversations with the class’s primary constructor when the class is in scope. An implicit class is a class marked with an ‘implicit’ keyword. This feature is introduced in Scala 2.10.

Syntax − The following is the syntax for implicit classes. Here implicit class is always in the object scope where all method definitions are allowed because the implicit class cannot be a top-level class.

Syntax

object <object name> {
  implicit class <class name>(<Variable>: Data type) {
      def <method>(): Unit =
  }
}

Singleton Objects

Scala is more object-oriented than Java because, in Scala, we cannot have static members. Instead, Scala has singleton objects. A singleton is a class that can have only one instance, i.e., Object. You create a singleton using the keyword object instead of the class keyword. Since you can't instantiate a singleton object, you can't pass parameters to the primary constructor. 

Post a Comment

0 Comments