zoukankan      html  css  js  c++  java
  • Scala使用备注一

    package com.ws.spark.study.scala
    
    import java.io.File
    import org.scalatest.FlatSpec
    import scala.io.Source
    
    class TestScala extends FlatSpec{
    
      "for循环" should "成功" ignore {
    
        // 1. for中增加多个过滤
        val files = new File(".").listFiles()
        for(
          file <- files
          if file.getName.endsWith(".xml");
          if file.isFile){
          println(file)
        }
    
        // 2. 多重for循环
        def fileLines(file: File) = Source.fromFile(file).getLines().toList
        def grep(pattern: String) =
          for{
            file <- files
            if file.getName.endsWith(".xml")
            line <- fileLines(file)
            if line.trim.matches(pattern)}{
            println(s"$file:${line.trim}")
          }
        grep("xml")
    
        // 3. 生成返回结果(Array[File] => Array[Int]的转换)
        val forLineLengths = for {
          file <- files if file.getName.endsWith(".xml")
          line <- fileLines(file)
          trimmed = line.trim if trimmed.matches(".*for.*")
        } yield trimmed.length
      }
    
      "list列表" should "success" ignore {
        // 1. 与Array不同的是,List中的值不能改变
    
        // 2. List具有协变性(Covariant),即类型S和T,如果S是T的子类,则List[S]也是List[T]的子类
        val list1: List[Object] = List("hello", "world")
    
        // 空List的类型为Nothing,Nothing是Scala继承层次中的最底层
        var list2: List[String] = List()
      }
    
      "函数参数" should "success" ignore {
        // 函数作为参数
        def convertIntToString(f: Int => String) = f(4) // 函数f作为参数
        val func = (x: Int) => s"$x s"
        println(convertIntToString(func)) // 4 s
    
        // 高阶函数可以产生新的函数
        def multiplyBy(factor: Double) = (x: Double) => factor * x
        val func2 = multiplyBy(10)
        func2(50)
      }
    
      "函数闭包" should "success" ignore {
    
        // 在运行时确定more类型及值得函数称为闭包, more是个自由变量,在运行时其值和类型得以确定
        // 这是一个由开放到封闭的过程,因此称为闭包
        var more = 1
        def func = (x: Int) => x + more
        println(func(10))
        more = 20
        println(func(10))
      }
    }
  • 相关阅读:
    洛谷 P1555 尴尬的数字
    洛谷 P1318 积水面积
    9.8解题报告
    洛谷 P1464 Function
    洛谷 P1122 最大子树和
    cogs 66. [HAOI2004模拟] 数列问题
    49. 跳马问题
    洛谷 P3137 [USACO16FEB]圆形谷仓Circular Barn_Silver
    codevs 3164 质因数分解
    codeforces 482C Game with Strings
  • 原文地址:https://www.cnblogs.com/mengrennwpu/p/11301302.html
Copyright © 2011-2022 走看看