Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
15
Help us understand the problem. What is going on with this article?
@bububu

Scalaのパターンマッチングを使った代入がすごい

More than 5 years have passed since last update.

Scala使いなら誰もがパターンマッチを使っていると思います


num match {
  case i: Int    => println("Int型だよ")
  case l: Long   => println("Long型だよ")
  case d: Double => println("Double型だよ")
}

opt match {
  case Some(x) => println(x)
  case None    => println("Noneだよ")
}

型ごとに分岐できたり
メンバの値を束縛することもできます。

実はパターンマッチは代入にも使えます
まずはパターンマッチに使うcase classを用意しましょう

case class Person(name: String, age: Int)

case classではunapplyメソッドが実装され

case Person(name, age) => println("名前: " + name + ", 年齢: " + age)

みたいにnameとageに値を束縛できます

これを変数代入でも出来ちゃうんです

val p: Person = Person("taro yamada", 25)
val Person(name, age) = p
println(name) // => taro yamada
println(age) // => 25

わざわざ
val name = p.name
val age = p.age
みたいに書かなくても一行で済みます

ただこれは結構知ってる人が多いんじゃないかと思うので
もう一つのパターンマッチのやり方も書きます

case class +(_1: Int, _2: Int)

何これと思う人がいると思うんですけど
実はこれ+が名前のcase classです

val a = new +(1, 2)

みたいなかんじで使えます
これをパターンマッチでどういう風に使うかというと

val b + c = a
println(b) // => 1
println(c) // => 2

b + cみたいに演算子を使うかのような感覚で代入できます
パターンマッチ超便利

15
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
bububu

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
15
Help us understand the problem. What is going on with this article?