Scala Tuple(元组)

Posted: 2020-03-08  By  vilay  |  Views(18)

元组与数组类似,但是数组中所有的元素必须是同一种类型,而元组则可以包含不同类型的元素

1. 定义

object TupleApp extends App {

val tuple = (1,"vilay")
println(tuple)
}

2. 模式匹配

object TupleApp extends App {

val tuple = (1,"vilay")
// println(tuple)

val (a,b) = tuple
println(a)
println(b)

val (c,_) = tuple  //不需要的可以通过_舍弃
println(a)
}

3. zip

var names = Array("vilay","zz")
var ages = Array(30,90)

var tup = ages.zip(names)
for (elem <- tup) {
    println(elem)
}

val newmap = ages.zip(names).toMap
for (el <- newmap) {
    println(el)
}