官术网_书友最值得收藏!

Tuple literals

Tuple is a data type in Scala. We'll discuss the type in this chapter later on. First, let's take a look at how we can define a literal of the same type:

scala> val aTuple = ("Val1", "Val2", "Val3")
aTuple: (String, String, String) = (Val1,Val2,Val3)
scala> println("Value1 is: " + aTuple._1)
Value1 is: Val1

Here, we defined a Tuple3, which took three parameters that are in parentheses and comma separated. Its type is going to be Tuple3, the same way we can define TupleN with N being 1 to 22. Take a closer look at the REPL response for the first declaration:

aTuple: (String, String, String) = (Val1,Val2,Val3)

Here aTuple has a Type (String, String, String), so as we assigned values to our identifier, aTuple Scala was able to construct type based on values we gave. Tuple values can be accessed using a special underscore syntax. Here, we use the tuple attribute name, along with an underscore (_), followed by the index of value. In our example, we're using val1, so we gave -aTuple._1 value.

A tuple with two elements is also called a Pair, it can be defined using the arrow assoc (->) operator:

scala> val smartPair = 1 -> "One"
smartPair: (Int, String) = (1,One)
主站蜘蛛池模板: 临颍县| 兰西县| 赫章县| 铜鼓县| 禄劝| 饶阳县| 霞浦县| 衢州市| 衡山县| 鄂尔多斯市| 彰化市| 越西县| 眉山市| 开平市| 安康市| 天峻县| 巴中市| 彭州市| 景谷| 合江县| 桃园县| 大足县| 察隅县| 阳新县| 个旧市| 宾川县| 甘南县| 扬州市| 桂东县| 巨野县| 长垣县| 宾川县| 遵义县| 长岭县| 哈巴河县| 桑植县| 宁阳县| 游戏| 三明市| 楚雄市| 嘉峪关市|