LoginSignup
2
1

More than 5 years have passed since last update.

Scalaのリストとタプル

Posted at

結論

タプルは型に関係無くまとめられるがリストは型に注意すべき。

同じ型をまとめたい時はタプルでもリストでもまとめられる。

case class Parson(first: String , last: String)

val me = new Parson("hiro", "t")
val you = new Parson("foo", "bar")
val tuple = (me, you)
// tuple: (Parson, Parson) = (Parson(hiro,t),Parson(foo,bar))
val list = List(me, you)
// list: List[Parson] = List(Parson(hiro,t), Parson(foo,bar))

しかし他の型も一緒にまとめたい時下記のようにしてしまうとタプルでは問題ないのに対しリストでは型の不一致によりうまくいかない。

case class Parson(first: String , last: String)
case class Baz(qux: Int)

val me = new Parson("hiro", "t")
val you = new Parson("foo", "bar")
val quxx = new Baz(777)
val tuple = (me, you, quxx)
// tuple: (Parson, Parson, Baz) = (Parson(hiro,t),Parson(foo,bar),Baz(777))
val list = List(me, you, quxx)
// list: List[Product with Serializable] = List(Parson(hiro,t), Parson(foo,bar), Baz(777))

tuple._1.first
// String = hiro
tuple._3.quzz
// Int = 777
list.head.first
// Product with Serializable = Parson(hiro,t)
list.last.quz
// Product with Serializable = Parson(hiro,t)

リストで違う型のものをまとめようとすると自動で型変換をしようとしてくれるみたいだけどそれがうまくいってないとこうなってしまうのかな?

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1