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))
  }
}
复制代码

 

posted @   mengrennwpu  阅读(347)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示