Introduction to Scala

Introduction to Scala

  • Scala is becoming popular
  • Twitter and Linkedin is using scala
  • Scala combines oop and functional programming
  • Scala has good support of concurrency

Install Scala

Scala Syntax

  • Example: Scala Version
  •   // create HelloWorldScala class with a singleton obejct
      object HelloWorldScala {
          // Array[String] equals to String[] in Java
          def main(args: Array[String]) {
              println("HelloScala")
          }
      }
    
  • Example: Java Version
  •   public class HelloWorldJava {
          public static void main(String[] args) {  
              System.out.println("HelloJava");
          }
      }
    
  • Difference:
    1. Singleton Object
      • Scala could declare members in singleton objects.
      • object HelloWorldScala will be created the first time it is used
    2. Multiple Objects
      •   // constructor; parameters with default values
          // val:T constants of type T
          // var:T variable of type T 
          class Point(var x: Int = 0, var y: Int = 0) { 
        
              // Question? why there is no "var"?
              // Unit == void in Java
              def move(dx: Int, dy: Int): Unit = {
                  x = x + dx
                  y = y + dy
              }
              // override parent's method
              // return type - String
              override def toString: String =
                  s"($x, $y)"
          }
        
          val point1 = new Point
          point1.x  //0
          println(point1)  //(0, 0)
        
          val point2 = new Point(2, 3)
          point2.x  //2
          println(point2)  //(2, 3)
        
          val point3 = new Point(y = 100)
          point3.move(50, -30)
          println(point3)  //(50, 70)    
        
    3. Companion Objects
      • Companiaon Objects are used to store static attributes or static methods.
          class Main {
              def nonStaticMethod() {
                  println("nonStaticMethod");
              }
          }
        
          // companion object to store static parts
          object Main {
              // a "static" variable
              val STATIC_FINAL_CONSTANT = "const"
              // a "static" method
              def staticMethod() {
                  println("staticMethod");
              }
          }
        
          var mainInstance : Main = new Main();
          mainInstance.nonStaticMethod(); // not Main.nonStaticMethod()
        
          Main.staticMethod(); // not mainInstance.staticMethod()
        
        
    4. public by Default
      • Class, method is declared as public by default
    5. Semicolon
      • Semicolons are only required if you have multiple statements in the same line.
    6. Scala Array
      • // Array(0,0,0,0,0,0,0,0,0,0)
        val nums = new Array[Int](10)
        val s = Array("Hello","World")
        // use () to access element
        println(s(0)) // Hello
        

A Spark Example with Scala

  • Skeleton Spark Code in Scala
  • import org.apache.spark.SparkContext
    // _ equals to * in Java
    import org.apache.spark.SparkContext._
    import org.apache.spark.SparkConf
    
    object SparkExample {
        def main(args:Array[String]){
            val conf = new SparkConf().setAppName("SparkExample")
            // start a new SparkContext
            val sc = new SparkContext(conf)
            // TODO
            sc.stop()
        }
    }
    

Declaring Value and Variables

  • constant and variables in Scala
  • var counter = 0 // declare an Int
    counter = 1 // OK, it can be changed as a var
    
    val language = "Scala" // declare as  a constant string
    language = "Java" // error 
    
  • Don’t have to declare type
    // don't have to od this since scala will detect the type automatically
    val greeting: String = "hello!"
    
  • Constant is encouraged to use in parallel
    • The result is indeterminate
    • Because multiple threads are access to num but we lack sychronization of it.
    • I don’t think this is a good example about why we should use val rather var …
  • object Increment {
        var num = 0
        def inc(): Unit = {
            num = num + 1
        }
    }
    
    class IncrementThread extends Runnable {
        def run(): Unit = {
            for (i <- 1 to 1000){
                Increment.inc()
            }
        }
    }
    
    object Threading {
        def main(args: Array[String]): Unit = {
            val threads = for (i <- 1 to 5) yield new Thread(new IncrementThread)
            for (thread <- threads) thread.start()
            for (thread <- threads) thread.join()
            print(Increment.num)
        }
    }
    

Types

  • All things are Objects in Scala (Like Python)
  • 1.toString() // this is feasible
    

Block Expressions and Assignments

  • Block is { sth }
  • The value of a block is the last expression in it
  • val x = 5
    val y = 7
    val distance = {
        val dx = x -2;
        val dy = y -3;
        math.sqrt(dx * dx + dy * dy)
    }
    // Here the value of distance is 5.0
    

Control Flow

  • if expression
    • if has a value (feature of functioanl languages)
    • since 1 and -1 are both Int, so the type of expression is also Int
    • val s = if (x > 0) 1 else -1
      # In Java, it will be
      # int s = x > 0 ? 1 : -1
      
    • if types are different, Any will be returned
    • // the value of the expression is Any
      // Any equals to Object in Java
      if (x > 0) "positive" else -1
      
    • if omit else part, the following two are equal
      if(x > 0) 1
      if(x > 0) 1 else () // () is a Unit in Scala
      

猜你喜欢

转载自blog.csdn.net/ZenG_xiangt/article/details/83305672
今日推荐