【问题标题】:What is the structure that is only enclosed by parentheses in scala?scala中仅用括号括起来的结构是什么?
【发布时间】:2015-02-03 13:19:23
【问题描述】:

问题来了:

我打算从函数中检索 (Int, Int) 对象,但我不知道如何获取第二个元素。我尝试了以下命令来检索第二个值,或者将其转换为 Seq 或 List,但没有运气。

scala> val s = (1,2)
s: (Int, Int) = (1,2)

scala> s(1)
<console>:9: error: (Int, Int) does not take parameters
              s(1)
               ^

scala> val ss = List(s)
ss: List[(Int, Int)] = List((1,2))

scala> ss(0)
res10: (Int, Int) = (1,2)

谁能给我一些想法?非常感谢!

【问题讨论】:

标签: scala


【解决方案1】:
val s = (1, 2)

是语法糖并创建一个Tuple2,或者换句话说等同于new Tuple2(1, 2)。您可以使用

访问元组中的元素
s._1 // => 1
s._2 // => 2

同样,(1, 2, 3) 将创建一个 Tuple3,它还有一个方法 _3 来访问第三个元素。

【讨论】:

  • 谢谢兄弟,这正是我需要的。实际上,如果你不给我这个提示,我什至不知道谷歌搜索什么关键字...... :]
  • 添加另一种提取元组内容的方法是模式匹配可能会很有用,例如:val (a, b) = (1, 2) 将影响 a=1, b=2。
猜你喜欢
  • 1970-01-01
  • 2012-09-12
  • 2012-02-12
  • 2015-09-08
  • 1970-01-01
  • 2011-08-14
  • 1970-01-01
  • 2010-12-13
相关资源
最近更新 更多