Scala Tutorial (2020) | TechGeekNext >>

Scala Tutorial (2020)

apache spark

What is Scala ?

Scala is a general-purpose programming language that runs on Java Virtual Machine (JVM) and .NET platforms

Scala is a functional language
  • Functions are first-class objects
  • Naturally supports concurrent and synchronous processing, parallel utilization of multicore CPUs, and cluster-based distributed processing
  • Provides a comprehensive library of immutable data structures
Scala is also an object-oriented language
  • Every value is an object, conceptually, and every operation is a method call
  • Many traditional design patterns are natively supported
  • Supports advanced component architectures, Inheritance and polymorphism, Classes can be concrete, abstract, implicit,or extended using traits

It Build solutions using the best of both paradigms, Migrate from OO while gaining confidence in functional techniques

Scala Java Compatibility

  • Scala compiles to Java bytecode and executes on a JVM
  • Existing Java APIs integrate seamlessly with Scala. So Scala has not needlessly reimplemented useful Java classes When appropriate, their use is encouraged!
  • More expressive import statement. Scala Uses the "_"character as wildcard as *is a valid identifier in Scala
  • Import multiple classes from the same package

Hello World in Scala :

object ScalaHelloWorld {
   def main(args: Array[String]) {
   val msg = "Hello World!"
Declared as a singleton using the object keyword
  • A class with a single instance
  • Created on demand the first time it is used
  • Provides a comprehensive library of immutable data structures
The main() method is not declared as static
  • Scala does not provide static fields and methods
  • The equivalent is to define these within singleton objects
  • The main() method does not return a value
  • It is not necessary to declare a return type for procedure methods

Scala Variables and Basic Syntax

Variable declarations in Scala are concise

  • The compiler infers type where possible
  • Strongly typed values are declared as mutable or immutable
  • Use varand val,respectively
  • val name: String = "The Scala programming language"
  • Or more concisely, using type inference
  • val name = "Scala programming"
  • Multiple assignment is also possible
  • val(title, name, age) = ("Dr", "Antony Jonson", 46)
Semicolons are optional for most statements
  • Required between multiple statements on a line
  • Multiline statements don't require a continuation character
Code blocks are grouped using { ... }as in Java, C/C++, etc
  • Supports inner scope variable shadowing

Basic Collection Types

Scala Numeric data types
  • Int, Long, Float, and Double
  • Provide .toDouble, .toFloat, .toInt, and .toLong where appropriate
The Boolean data type
The String data type
  • Literals are enclosed in ""characters
  • The + operator can be used for concatenation, However, interpolation is preferred
  • println(s"The request returned $n rows")
    println(s"The amount including 20% tax is 0.0")
Scala supports tuples
  • Nestable collections of items
  • Element type is inferred
  • val person = ("Dr John", 81, ("Sunnywell", "CA", "USA"))
    val name = person._1
    val state = person._3._2

Basic Collection Types

  • Similar to Listin Java
  • val primes = Seq(2, 3, 5, 7, 11, 13 )
    val lines = Seq( (1, "The dog"), (2, "sat on the cot") )
    lines.foreach{ case(n, txt) => println(s"#$n = $txt") }
  • Using pattern matching to access the Seqtuple components
    val names = Array( "Scala", "Java", ".Net" )
    val lines = new Array[String](100)
    lines(3) = "The dog sat on the cot"
    val matrix = Array.ofDim[Int](3, 3)
    matrix(1)(2) = -1
Provide .toSeq and .toArray methods where appropriate

Some MLlib-specific collections : Vector, Matrix, and RowMatrix, etc.

A Scala Mapis a collection of key/value pairs
  • Often referred to as a dictionary in other languages
  • var asciiMap: Map[ Char, Int ] = Map()
    asciiMap += ('a' -> 97)
    asciiMap += ('z' -> 122) // Note: this is a mutable Map
    val lookup = asciiMap('z')
    val rgb = Map( "red" -> "#FF0000", "green" -> "#00FF00",
    "blue" -> "#0000FF" )
    rgb.keys.foreach{ key =>
    print( s"Key = $key, " )
    println( s"Value = $ {rgb(key)}" )
    rgb.foreach{ case(k, v) => println(s"$k = $v") }
  • Some of the many usefulMap methods
  • +,++,-, --, keys,values,filterKeys,mapValues,get,getOrElse,contains,isEmpty,count,remove,clear,toString,toArray
Scala method and function definitions have the following form
  • Can specify return statements at any point in the body, If omitted, returns the value of the final statement
  • Nesting is supported
  • Often specified as anonymous literals
def methodName ([list of parameters]): [return type] = {
   method body
   return [expr]
// a simple function with an inferred return type
def add(a: Int, b: Int) = {
  a + b
val list = Seq(1, 2, 3, 4)
val sum = list.reduceLeft( (x, y) => x + y ) // an anonymous literal or lambda
val sigma = list.reduceLeft( _ + _ ) // using compact lambda syntax

Recommendation for Top Popular Post :