【scala 匹配模式】match case|case class |::|:::|=>用法

主要内容:

  • 1、Scala的匹配模式(标准用法(match)/使用守卫/匹配类型)
  • 2、Scala的case class,多用在匹配模式中
  • 3、Scala中 :: 和 ::: 冒号的使用情况
  • 4、Scala中 => 映射作用

一、Scala的匹配模式(标准用法(match)/使用守卫/匹配类型)

package DataStructureAndAlgorithm

/**
  * Created by Administrator on 2017/12/23.
  */
object Test17ScalaMatch {
  def main(args: Array[String]) {
    val value = 3
    // 标准用法(match)
    val result = value match {
      case 1 => "one"
      case 2 => "two"
      case _ => "other"
    }
    println("result of match is : " + result)


    // 使用守卫
    val result2 = value match {
      case i if i ==1 => "one_1"
      case i if i ==2 => "two_2"
      case i if i ==3 => "other_2"
    }
    println("result of match is : " + result2)


    // 匹配类型
    def t(obj: Any) = obj match {
      case x: Int => println("Int")
      case s: String => println("String")
      case _ => println("unknown type")
    }
    t(1)
    t("a")
    t(1L)
  }
}
result of match is : other
result of match is : other_2
Int
String
unknown type

Process finished with exit code 0

二、case class 多用在模式匹配中

  • case class 默认类型是: val
  • 构造器中的每一个类型都是val, 不建议用var.
  • 不用new就可以直接产生对象(为什么? apply方法)
package DataStructureAndAlgorithm

/**
  * Created by Administrator on 2017/12/23.
  */
/*
case class 多用在模式匹配中
  case class 默认类型是: val
  构造器中的每一个类型都是val, 不建议用var.
  不用new就可以直接产生对象(为什么? apply方法)
 */
case class Book(name: String, author: String)

object Test18ScalaCaseClass {
  def main(args: Array[String]) {
    val macTalk = Book("MacTalk", "CJQ")
    macTalk match {
      case Book(name, author) => println("this is a book")
      case _ => println("unknown")
    }

  }
}

运行结果:

this is a book

Process finished with exit code 0

三、Scala中 :: 和 ::: 冒号的使用情况

def ::(x: B): List[B]
def :::(prefix: List[B]): List[B]
def ::(x: B): List[B]

Example:
1 :: List(2, 3) = List(2, 3).::(1) = List(1, 2, 3)

中文解释就是 => 元素 :: 数组,表示在数组的首位添加元素

def :::(prefix: List[B]): List[B]

Example:
List(1, 2) ::: List(3, 4) = List(3, 4).:::(List(1, 2)) = List(1, 2, 3, 4)

中文解释就是 => 数组1 ::: 数组2,表示在 数组2 的 首位 添加 数组1

四、Scala中 => 映射作用

var increase = (x: Int) => x + 1
increase(10)
res0: Int = 11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

东华果汁哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值