Scala元组用法示例

元组是有序形式的元素的集合。如果不存在任何元素, 则称为空元组。你可以使用元组来存储任何类型的数据。你也可以存储类似类型或混合类型的数据。你可以使用它从一个函数返回多个值


Scala元组示例

在以下示例中, 我们创建了不同类型元素的元组。

object MainObject{
    def main(args:Array[String]){
        var tuple = (1, 5, 8, 6, 4)     				// Tuple of integer values
        var tuple2 = ("Apple", "Banana", "Gavava")    	// Tuple of string values
        var tuple3 = (2.5, 8.4, 10.50)    			// Tuple of float values
        var tuple4 = (1, 2.5, "India")    			// Tuple of mix type values
        println(tuple)
        println(tuple2)
        println(tuple3)
        println(tuple4)
    }
}

输出

(1, 5, 8, 6, 4)
(Apple, Banana, Gavava)
(2.5, 8.4, 10.5)
(1, 2.5, India)

Scala元组示例:访问元组元素

在此示例中, 我们使用索引访问元组元素。在这里, 我们使用productIterator来迭代元组元素。

object MainObject{
    def main(args:Array[String]){
        var tupleValues = (1, 2.5, "India")
        println("iterating values: ")
        tupleValues.productIterator.foreach(println)    // Iterating tuple values using productIterator
        println("Accessing values: ")
        println(tupleValues._1) // Fetching first value
        println(tupleValues._2) // Fetching second value
    }
}

输出

iterating values: 
1
2.5
India
Accessing values: 
1
2.5
微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_47714.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?