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

Community
Service
Qiita JobsQiita ZineQiita Blog
27
Help us understand the problem. What is going on with this article?

More than 5 years have passed since last update.

@petitviolet

# [Scala]パターンマッチにおけるアットマーク(@)

## 問題

こんなコードがある

``````def flatMapSublists[A,B](ls: List[A])(f: (List[A]) => List[B]): List[B] =
ls match {
case Nil => Nil
case sublist@(_ :: tail) => f(sublist) ::: flatMapSublists(tail)(f)
}
``````

## 意味

パターンマッチを行う際に`foo@bar`で、`bar`にマッチしたものを`foo`にバインドするということらしい
つまり、上の例では`ls``_ :: tail`にマッチするようなものだった場合に、`ls``sublist`にバインドされる

### 他の例

そうであった場合に、標準出力しながら、リストの2番目(indexは1)の要素を取得したいとき

``````val something = List(1, 2, 3)
something match {
case ls@List(_,elem,_) => println("matching:" + ls); elem
}
// res: AnyVal = 2

// @を使わずに同様のことを行う
something match {
case List(a,elem,b) => println("matching:" + List(a,elem,b)); elem
}
// res: AnyVal = 2

// これでも良い
something match {
case List(a,elem,b) => println("matching:" + something); elem
}

``````

`ls@`なんて付けずに`something`をそのまま使えばいいんじゃね？って思った
よくわからんのでもう少し

``````val list = List(1, 2, 3)

list match {
case ls@(h :: tail) => println(tail); list
case Nil => Nil
}
// List(2, 3)
// res: List[Int] = List(1, 2, 3)

list match {
case ls@(h :: tail) => println(tail); ls
case Nil => Nil
}
// List(2, 3)
// res: List[Int] with Serializable = List(1, 2, 3)

``````

なぜか`Serializable`になった
この`@`には名前がないのかな

27
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
27
Help us understand the problem. What is going on with this article?