zoukankan      html  css  js  c++  java
  • scala学习手记40

    再来看一下之前的一段代码:

    def process(input: Any) {
      input match {
      case (a: Int, b: Int) => println("Processing (int, int)... ")
      case (a: Double, b: Double) => println("Processing (double, double)... ")
      case msg: Int if (msg > 1000000) => println("Processing int > 1000000")
      case msg: Int => println("Processing int... ")
      case msg: String => println("Processing string... ")
      case _ => printf("Can't handle %s... ", input)
      }
    }

    在上面的代码里出现了三个占位符a, b和msg。他们就是占位符。

    按照约定,Scala中模式变量要以小写字母开头,常量要以大写字母开头。所以这里一定要注意大小写,这里就是一个出错的实例:

    class Sample {
      val max = 100
      val MIN = 0
      def process(input: Int) {
        input match {
          case max => println("Don't try this at home")
          case MIN => println("You matched min")
          case _ => println("Unreachable!!")
        }
      }
    }

    虽然程序可以执行,但是在执行的时候会给出警告:

    image

    提示模式变量的模式无法匹配。执行结果也和预期严重不一致。执行的代码:

    new Sample().process(100)
    new Sample().process(0)
    new Sample().process(10)

    执行结果:

    image

    如果偏要使用这个值的话可以通过对象或类来引用这个变量:

    class Sample {
      val max = 100
      val MIN = 0
      def process(input: Int) {
        input match {
          case this.max => println("Don't try this at home")
          case MIN => println("You matched min")
          case _ => println("Unreachable!!")
        }
      }
    }
    
    new Sample().process(100)
    new Sample().process(0)
    new Sample().process(10)

    此时的执行结果是正确的:

    image

    就这样!

    ######

  • 相关阅读:
    程序员常用英语词汇
    声明式编程与命令式编程
    vue 常用ui组件库
    Vue 组件之间传值
    vscode插件之背景插件(background)
    iconfont的使用
    CSS3 @font-face 规则
    CSS抗锯齿 font-smoothing 属性介绍
    new Image 读取宽高为0——onload
    js的for循环中出现异步函数,回调引用的循环值始终是最后的值
  • 原文地址:https://www.cnblogs.com/amunote/p/5883346.html
Copyright © 2011-2022 走看看