zoukankan      html  css  js  c++  java
  • 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,"	",v1.b)
        println(v2.a,"	",v2.b)
    
        //update的使用
        v2.update((5,6))
        v2()=(7,8)
    
        //unapply的使用
        val ApplyDemo(a,b) = v2
        println(a,"	",b)
    
      }
    }
    渐变 --> 突变
  • 相关阅读:
    递归的用法
    冒泡排序
    Python_MySQL:MySQL常用命令
    开发Python项目案例,这8个库不容错过,功能强大性能优质
    pyQuery CSS选择器
    数据结构——快速排序(使用Java)
    spring security 动态配置登出页面
    String、StringBuffer和StringBuilder
    vue部署项目刷新404的解决方案
    String数组常用的几种遍历方法
  • 原文地址:https://www.cnblogs.com/lybpy/p/9738925.html
Copyright © 2011-2022 走看看