Scala下划线用法

  1. 导包时导入包下的所有类
    import java.text.DateFormat._
  1. 模式匹配中最后一个匹配项,匹配任意值
    def derive(t: Tree, v: String): Tree = t match {
     case Sum(l, r) => Sum(derive(l, v), derive(r, v))
     case Var(n) if (v == n) => Const(1)
     case _ => Const(0)
   }
  1. 代表默认值,①数值类型:0;②布尔类型:false;③Unit:();④其他对象类型:null
    class Reference[T] {
    private var contents: T = _
    def set(value: T): Unit = { contents = value }
    def get: T = contents
  }
  1. 在getter标识符后添加"_=(参数列表)"作为setter
      def x = _x
      def x_= (newValue: Int): Unit = {
        _x = newValue
      }
  1. 访问元组的元素
    val ingredient = ("Sugar" , 25)
    println(ingredient._1) // Sugar
    println(ingredient._2) // 25
  1. 匿名函数中省略入参时作为参数名
    val salaries = Seq(20000, 70000, 40000)
    val newSalaries = salaries.map(_ * 2)
  1. 函数柯里化中的部分应用(对于多参数列表的方法,若只传入其中一些参数列表时会生成一个以缺失的参数列表作为其参数的函数)
    trait Iterable[A] {
      ...
      def foldLeft[B](z: B)(op: (B, A) => B): B
      ...
    }
    val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    val numberFunc = numbers.foldLeft(List[Int]()) _
    val squares = numberFunc((xs, x) => xs :+ x*x)
    println(squares)// List(1, 4, 9, 16, 25, 36, 49, 64, 81, 100)
  1. 序列作为方法中的不定长参数的入参
      def average(x: Int, xs: Int*): Double =
      (x :: xs.toList).sum.toDouble / (xs.size + 1)

      val d = average(1, List(2, 3):_*)
      println(d) // 2.0

posted on 2021-11-04 15:10  Deemoo  阅读(31)  评论(0编辑  收藏  举报

导航