zoukankan      html  css  js  c++  java
  • scala 模式匹配

    https://blog.csdn.net/bluishglc/article/details/50995939


    scala> val a = Array(1,2,3,4) a: Array[Int] = Array(1, 2, 3, 4)

    匿名函数,由繁入简,

     使用case语句构造匿名函数的“额外”好处,

     case语句(组合)除了可以被编译为匿名函数(类型是FunctionX,在Scala里,所有的函数字面量都是一个对象,这个对象的类型是FunctionX),还可以非常方便的编译为一个偏函数PartialFunction!(注意:PartialFunction同时是Function1的子类)编译器会根据调用处的函数类型声明自动帮我们判定如何编译这个case语句(组合)

     case语句声明的变量就是偏函数的参数,既然case语句只能声明一个变量,那么偏函数受限于此,也只能有一个参数!

    
    scala> a.map(x => x match {
         |   case 0 => "zero"
         |   case 1 => "one"
         |   case 2 => "two"
         |   case _ => "other"
         | })
    res2: Array[String] = Array(one, two, other, other)
    
    
    scala> a.map(x => x match { case x => x })
    res4: Array[Int] = Array(1, 2, 3, 4)
    
    
    
    scala> a.map(case x => x)
    <console>:1: error: illegal start of simple expression
    a.map(case x => x)
          ^
    
    
    scala> a.map{case x => x}
    res3: Array[Int] = Array(1, 2, 3, 4)
    
    
    scala> a.map{x => x}
    res7: Array[Int] = Array(1, 2, 3, 4)
  • 相关阅读:
    十几个remote control software
    chromedriver bug
    跟我一起学ruby (转)
    ruby两套教程
    java把函数作为参数传递
    java如何在函数中调用主函数的数组
    Java HashSet和LinkedHashSet的用法
    java文件读写操作
    RAID详细介绍
    Apriori算法
  • 原文地址:https://www.cnblogs.com/TMatrix52/p/12080594.html
Copyright © 2011-2022 走看看