• 【Scala】快速入门


    参考资料:B站林子雨教学视频


    变量

    变量声明

    • var 可变
    • val 不可变;字面量(literal)用val
    val valDouble: Double = 10.6
    var varStr: String = "Hello Scala!"
    varStr = "Hello World!"
    // valDouble = 10.8 不可更改
    
    • 1
    • 2
    • 3
    • 4

    基本数据类型

    • Byte Short Int Long
    • Char String
    • Float Double
    • Boolean

    这些类型都是类

    操作符

    注意:操作符是方法

    (5).+(3.5) == 5.5 + 3 	// true
    
    • 1

    Range

    1 to 5
    6.to(10)
    1 until 5
    1 to 10 by 2
    0.5f to 6.0f by 0.5f
    
    • 1
    • 2
    • 3
    • 4
    • 5

    控制台输入输出

    • 输入 readByte, readShort, readInt, readLong, readFloat, readchar, readBoolean 等等
    • 输出 print, println, prinf
    var age = readInt()
    var heavy = readFloat()
    var str = readLine("Please input your name: ")
    printf("My name is %s. I am %d years old and %.1f Kg.\n", str, age, heavy)
    
    • 1
    • 2
    • 3
    • 4

    文件读写

    写文件

    import java.io.PrintWriter
    val out = new PrintWriter("output/output.txt")
    for (i <- 1 to 5) out.println(1)
    out.close()
    
    • 1
    • 2
    • 3
    • 4

    读文件

    import scala.io.Source
    val inputFile = Source.fromFile("input/words.txt")
    val lines = inputFile.getLines() // 返回的是一个迭代器
    for (line <- lines) println(line)
    
    • 1
    • 2
    • 3
    • 4

    异常处理

    Scala只有不受检查异常

    var f: FileReader = null
    try {
        f = new FileReader("input.txt")
    } catch {
        case ex: FileNotFoundException =>
        	println("Exception: File Not Found!")
        case ex: IOException =>
        	println("IO Exception!")
    } finally {
        try {
            f.close()
        } catch {
            case ex: NullPointerException =>
            	println("Null Pointer Exception!")
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    控制结构

    if

    语法同Java一样,但和Python一样可以赋值

    val a = if (true) 1 else 0
    
    • 1

    while、do while

    var i = 3
    while (i > 0) {
        println(i)
        i -= 1
    }
    
    do {
        i -= 1
        println(i)
    } while (i > -3)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    for

    • for (变量 <- 表达式) 语句块
    • 括号内称为生成器generator
    • 支持if过滤条件,称为guard
    for (i <- 1 to 5 by 2) println(i)
    for (i <- 6 to 10 if i%2 == 0) println(i)
    for (i <- 1 to 5 if i%2 == 0; j <- 6 to 10 if j%2 == 1)
    	println(i + "*" + j + "=" + i*j)
    
    • 1
    • 2
    • 3
    • 4
    val r = for (i <- 1 to 10 if i%2 == 0) yield {println(i); i}
    println(r)	// Vector(2, 4, 6, 8, 10)
    
    • 1
    • 2

    数据结构

    Collection

    • scala.collection.mutable
    • scala.collection.immutable

    List

    • 共享相同类型
    • 不可变的对象序列
    • scala.collection.immutable.List
    var strList = List("BigData", "Hadoop", "Spark")
    for (item <- strList) println(item)
    
    • 1
    • 2
    // tail输出除head之外的全部
    strList.head, strList.tail 
    // (BigData,List(Hadoop, Spark))
    
    • 1
    • 2
    • 3
    // 把Apache插入到strList头部
    var otherList = "Apache"::strList
    for (item <- otherList) println(item)
    
    • 1
    • 2
    • 3
    val intList = 1::2::3::Nil 
    // 等效于 val intList = List(1, 2, 3)
    
    • 1
    • 2

    Set

    • 不重复,无序
    • 缺省情况下创建的是不可变集
      • scala.collection.immutable.Set
      • scala.collection.mutable.Set
    var strSet = Set("Hadoop", "Spark")
    var copySet = strSet
    
    strSet += "Scala"  // strSet指向变了, 即不再指向原先那个Set了
    
    for (item <- strSet) println("new: " + item)
    for (item <- copySet) println("copy: " + item)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    // 声明可变集合 可 import; 也可 声明变量时写全名
    // import scala.collection.mutable.Set
    val mutableSet = scala.collection.mutable.Set("DataBase", "BigData")
    val copyMutableSet = mutableSet
    
    mutableSet += "Cloud Computing"  // 指针指向没变,与它是val并不矛盾
    
    for (item <- mutableSet) println("new: " + item)
    for (item <- copyMutableSet) println("copy: " + item)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    Map

    • 默认情况下使用不可变映射
      • scala.collection.immutable.Map
      • scala.collection.mutable.Map
    • key不存在时会抛出异常
    val university = Map("XMU" -> "Xiamen University",
                         "THU" -> "Tsinghua University",
                         "PKU" -> "Peking University")
    val xmu = if (university.contains("XMU")) university("XMU") else 0
    
    • 1
    • 2
    • 3
    • 4
    val university2 = scala.collection.mutable.Map("XMU" -> "XMU")
    
    // 修改value
    university2("XMU") = "Xiamen University"
    
    // 新增键值对
    university2("PKU") = "Peking University"
    university2 += ("THU" -> "Tsinghua University")
    university2 += ("SDU" -> "ShanDong University", "SJU" -> "Jiaotong University")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    // Map的几种遍历方式
    for ((k, v) <- university2) printf("Code is %s, Name is %s.\n", k, v)
    for (kv <- university2) println(kv._1 + ": " + kv._2)
    for (k <- university2.keys) println(k)
    for (v <- university2.values) println(v)
    
    • 1
    • 2
    • 3
    • 4
    • 5

    迭代器

    • 常规遍历
    var iter = Iterator("Hadoop", "Spark", "Scala")
    while (iter.hasNext) {
        println(iter.next())
    }
    
    // 迭代器已经到末尾了 必须重新赋值
    iter = Iterator("Hadoop", "Spark", "BigData")
    for (elem <- iter) println(elem)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • grouped
    val xs = List(1, 2, 3, 4, 5)
    
    // 每两个一组
    // 也可以写成 xs grouped 2
    val git = xs grouped(2) 
    
    while (git.hasNext) {
        println(git.next())
    }
    // List(1, 2)
    // List(3, 4)
    // List(5)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • sliding
    // 以3为滑动窗口size, 一直滑到end
    val sit = xs sliding 3
    while (sit.hasNext) {
        println(sit.next())
    }
    
    // List(1, 2, 3)
    // List(2, 3, 4)
    // List(3, 4, 5)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    Array

    • 定长 可变 可索引 共享相同类型
    • new Array[type](length)
    • 索引用圆括号
    • 多维数组 Array.ofDim[type](dim0, dim1, ...)
    val intValueArr = Array(-12, 45, 33)
    intValueArr(0) = 12
    
    • 1
    • 2
    val strArr = new Array[String](3)
    strArr(0) = "BigData"
    strArr(1) = "Hadoop"
    strArr(2) = "Spark"
    
    • 1
    • 2
    • 3
    • 4
    // 数组遍历
    for (i <- 0 to 2) println(intValueArr(i) + " " + strArr(i))
    
    • 1
    • 2
    // 多维数组
    val matrix = Array.ofDim[Int](3, 4)
    val cube = Array.ofDim[Int](3, 4, 5)
    
    • 1
    • 2
    • 3

    ArrayBuffer

    不定长数组

    val aMutableArr = ArrayBuffer(10, 20)
    
    // 末尾追加50
    aMutableArr += 50
    for (num <- aMutableArr) println(num)
    
    // 在第3个位置插入两个数
    aMutableArr.insert(2, 30, 40)
    for (num <- aMutableArr) println(num)
    
    // 删去40这个数
    aMutableArr -= 40
    for (num <- aMutableArr) println(num)
    
    // 移除第3个数
    aMutableArr.remove(2)
    for (num <- aMutableArr) println(num)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    Tuple

    不同类型的值的聚集

    val tuple = ("BigData", 2015, 45.0, true)
    println(tuple._1 + " " + tuple._2 + " " + tuple._3 + " " + tuple._4)
    
    • 1
    • 2

    模式匹配

    在异常处理部分有简单涉及

    // 有匹配值 输出red
    val colorNum = 1
    var colorStr = colorNum match {
        case 1 => "red"
        case 2 => "green"
        case 3 => "yellow"
        case _ => "Not Allowed"
    }
    println(colorStr)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    // 可捕获值并利用该值
    colorStr = 4 match {
        case 1 => "red"
        case 2 => "green"
        case 3 => "yellow"
        case unexpected => unexpected + " is Not Allowed"
    }
    println(colorStr)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    // 也可以match类型
    for (elem <- List(3, 9.3, "Spark", "Hadoop", true)) {
        val str = elem match {
            case i: Int => i + " is an int value."
            case d: Double => d + " is a double value."
            case "Spark" => "Spark is found."
            case s: String => s + " is a string value."
            case _ => "This is an unexpected value."
        }
        println(str)
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    // 支持条件过滤
    for (elem <- List(1, 2, 3, 4)) {
        elem match {
            case _ if (elem%2 == 0) => println(elem + " is even.")
            case _ => println(elem + " is odd.")
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    // case类的匹配
    case class Car(brand: String, price: Int)
    val myBYDCar = new Car("BYD", 89)
    val myBMWCar = new Car("BMW", 120)
    val myBenzCar = new Car("Benz", 150)
    
    case class Car(brand: String, price: Int)
    val myBYDCar = new Car("BYD", 89)
    val myBMWCar = new Car("BMW", 120)
    val myBenzCar = new Car("Benz", 150)
    for (car <- List(myBYDCar, myBMWCar, myBenzCar)) {
        car match {
            case Car("BYD", 89) => println("Hello, BYD")
            case Car("BMW", 120) => println("Hello, BMW")
            case Car(brand, price) => println("Brand: " + brand + ", Price: " + price + ", do you want it?")
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    Option类型

    val books = Map("Hadoop" -> 5, "Spark" -> 10, "HBase" -> 7)
    
    println(books.get("Hadoop")) // Some(5) 
    
    val sales = books.get("Hive")
    println(sales) // None
    
    // 把None转化为No Such Book
    println(sales.getOrElse("No Such Book"))
    
    println(List(1, null).foreach(println))
    // 1
    // null
    // () foreach遇到None的时候
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
  • 相关阅读:
    电脑C盘怎么清理到最干净
    小分子PEG CAS:1352814-07-3生物素-PEG6-丙酸叔丁酯
    基于微信小程序的宠物寄养小程序,附源码
    CMU 15-445 Project 0 实现字典树
    IntelliJ IDEA使用——Debug操作
    【MySQL】表的约束
    避免代价高昂的 ECM 集成错误的 3 个技巧
    【java】ArrayList和LInkedList的区别
    Trace 在多线程异步体系下传递最佳实践
    springcloud-网关(gateway)
  • 原文地址:https://blog.csdn.net/m0_46459047/article/details/126830254