7、中置、一元、赋值、结合、apply和update、unapply提取器

中置操作符

scala> 1 to 5
res0: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5)

scala> 1 -> 2
res1: (Int, Int) = (1,2)

scala> 1 until 5
res2: scala.collection.immutable.Range = Range(1, 2, 3, 4)

一元操作符

scala> ~1
res3: Int = -2

scala> -1
res4: Int = -1

scala> +1
res5: Int = 1

scala> 1.unary_~
res6: Int = -2

scala> 1.unary_-
res7: Int = -1

scala> 1.unary_+
res8: Int = 1

赋值操作符

结合性:以 : 结尾的操作符,都是右操作符

scala> 4 +: arr
res23: Array[Int] = Array(4, 1, 2, 3)

scala> arr.+:(4)
res24: Array[Int] = Array(4, 1, 2, 3)

scala> arr :+ 4
res25: Array[Int] = Array(1, 2, 3, 4)

scala> arr.:+(4)
res28: Array[Int] = Array(1, 2, 3, 4)
scala> 1::2::3::Nil
res29: List[Int] = List(1, 2, 3)

apply和update

可自定义apply和update方法

f(arg1,arg2,arg3) 等同于    f.apply(arg1,arg2,arg3)  定义在伴生对象中

如果出现在赋值语句左侧:f(arg1,arg2,arg3) = value,则等同于 f.update(arg1,arg2,arg3,value)  定义在类中

 

unapply

  Option 可空:None空和Some有值

  Fac(a,b) = f

class ApplyDemo(var a:Int,var b:Int) {

  def update(ab:(Int,Int)): Unit ={
    this.a = ab._1
    this.b = ab._2
  }
}

object ApplyDemo {
  def apply(a: Int, b: Int): ApplyDemo = new ApplyDemo(a, b)

  def unapply(arg: ApplyDemo): Option[(Int, Int)] ={
    if(arg.b == 0)None else Some((arg.a,arg.b))
  }

  def main(args: Array[String]): Unit = {
    //apply的使用
    val v1 = new ApplyDemo(1,2)
    val v2 = ApplyDemo(3,4)

    println(v1.a,"\t",v1.b)
    println(v2.a,"\t",v2.b)

    //update的使用
    v2.update((5,6))
    v2()=(7,8)

    //unapply的使用
    val ApplyDemo(a,b) = v2
    println(a,"\t",b)

  }
}

 

7、中置、一元、赋值、结合、apply和update、unapply提取器

上一篇:The Anatomy of a Large-Scale Hypertextual Web Search Engine


下一篇:java(android)命名规范