[learning Scala] data structure

本文深入探讨Scala语言的核心特性,通过具体实例展示了如何利用其强大的表达能力进行复杂操作,包括元组使用、条件判断、匹配模式、迭代器等。同时,文章还涉及了变量赋值、函数式编程思想的应用,以及错误处理机制。通过简洁明了的代码示例,旨在帮助开发者掌握Scala编程的精髓。
object SparkTest002 {
  def main(args: Array[String]): Unit = {

    //date : 2015/12/29
    //tuple test
    val info = (5, "test", true)
    print(s"first: ${info._1}, second: ${info._2}, third: ${info._3}\n")

    val kv = "src" -> "dst"
    print(s"first: ${kv._1}, second: ${kv._2}\n")



    /*
     * Chapter 3: Expressions and Conditionals
     */
    val amount = {
      val x = 5 * 20
      x > 100
    }
    print(s"amount is : ${amount}\n")

    val trippleNested = {
      val a = 1;
      {
        val b = a + 2;
        {
          val c = b + 4
          c
        }
      }
    }
    print(s"trippleNested : ${trippleNested}\n")

    if (1 > 0) print("1 bigger than 0\n")

    val x = 2;
    val y = 3;
    var res1 = if (x < y) x else y
    val res2 = if (x > 100000) x // not safe, missed else branch
    print(s"res: ${res2}\n")

    val res3 = x > y match {
      case true => {
        x * 2
      }
      case false => {
        y * 2
      }
    }
    print(s"res: ${res3}\n")

    val date = "monday"
    val isValid = date match { // scala MatchError when missing the wildcard operator
      case "mon" | "tue" => "yes"
      case "thu" | "wen" => "no"
      case _ => ""
    }
    print(s"isValid: ${isValid}\n")

    for (i <- 1 to 3) print(s"count: ${i}\n")

    print("\n")
    for (i <- 1 until 3) print(s"count: ${i}\n")

    print("\n")
    val record = for (i <- 1 to 5) yield {i}
    print(s"record size: ${record.size}\n")
    for (i <- 1 to 5) print(s"${i}\n")

    val odds = for (i <- 0 to 15 if i % 3 == 0) yield i
    for (i <- odds) print(s"num: ${i}\n")

    val line = "hello,world,,!"
    for {
      s <- line.split(",")
      if s != null
      if s.size != 0
    } {
      print(s"word: ${s}\n")
    }

    // nested iterators
    for {
      x <- 1 to 2
      y <- 1 to 3
    } {
      print(s"nested value: ($x, $y)\n")
    }

    // value binding in for loop
    val pows = for (i <- 0 to 8; pow = 1 << i) yield pow
    for (i <- pows) print(s"$i\t")
    val pows1 = for {
      i <- 0 to 10
      pow = 1 << i
    } {
      print(s"$pow\t")
    }
  }
}

 

转载于:https://www.cnblogs.com/alexander-chao/p/5092304.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值