关于scala元组的简单问题

Fre*_*ind 23 scala tuples

我是斯卡拉的新手,我正在学习的是tuple.

我可以定义一个元组如下,并获取项目:

val tuple = ("Mike", 40, "New York")
println("Name: " + tuple._1)
println("Age: " + tuple._2)
println("City: " + tuple._3)
Run Code Online (Sandbox Code Playgroud)

我的问题是:

  1. 如何获得元组的长度?
  2. 元组是否可变?我可以修改它的项目吗?
  3. 我们可以在元组上做任何其他有用的操作吗?

提前致谢!

mis*_*tor 41

1] tuple.productArity

2]不.

3]你可以对元组执行一些有趣的操作:(简短的REPL会话)

scala> val x = (3, "hello")
x: (Int, java.lang.String) = (3,hello)

scala> x.swap
res0: (java.lang.String, Int) = (hello,3)

scala> x.toString
res1: java.lang.String = (3,hello)

scala> val y = (3, "hello")
y: (Int, java.lang.String) = (3,hello)

scala> x == y
res2: Boolean = true

scala> x.productPrefix
res3: java.lang.String = Tuple2

scala> val xi = x.productIterator
xi: Iterator[Any] = non-empty iterator

scala> while(xi.hasNext) println(xi.next)
3
hello
Run Code Online (Sandbox Code Playgroud)

有关更多内容,请参阅Tuple2 ,Tuple3等的scaladocs.


oll*_*erg 17

你也可以用元组做的一件事是使用match表达式提取内容:

def tupleview( tup: Any ){
  tup match {
    case (a: String, b: String) =>
      println("A pair  of strings: "+a + " "+ b)
    case (a: Int, b: Int, c: Int) =>
      println("A triplet of ints: "+a + " "+ b + " " +c)
    case _ => println("Unknown")
  }
}

tupleview( ("Hello", "Freewind"))
tupleview( (1,2,3))
Run Code Online (Sandbox Code Playgroud)

得到:

A pair  of strings: Hello Freewind
A triplet of ints: 1 2 3
Run Code Online (Sandbox Code Playgroud)


ret*_*nym 11

Tuples是不可变的,但是,像所有case类一样,它们有一个copy方法,可以用来创建一个Tuple带有一些更改元素的new :

scala> (1, false, "two")
res0: (Int, Boolean, java.lang.String) = (1,false,two)

scala> res0.copy(_2 = true)
res1: (Int, Boolean, java.lang.String) = (1,true,two)

scala> res1.copy(_1 = 1f)
res2: (Float, Boolean, java.lang.String) = (1.0,true,two)
Run Code Online (Sandbox Code Playgroud)


Lan*_*dei 7

关于问题3:

使用Tuples可以做的一件有用的事情是存储函数的参数列表:

def f(i:Int, s:String, c:Char) = s * i + c
List((3, "cha", '!'), (2, "bora", '.')).foreach(t => println((f _).tupled(t)))
//--> chachacha!
//--> borabora.
Run Code Online (Sandbox Code Playgroud)

[编辑]正如兰德尔所说,你最好在"现实生活"中使用这样的东西:

def f(i:Int, s:String, c:Char) = s * i + c
val g = (f _).tupled
List((3, "cha", '!'), (2, "bora", '.')).foreach(t => println(g(t)))
Run Code Online (Sandbox Code Playgroud)

为了从"集合转换链"中间的元组中提取值,您可以编写:

val words = List((3, "cha"),(2, "bora")).map{ case(i,s) => s * i }
Run Code Online (Sandbox Code Playgroud)

注意案例周围的花括号,括号不起作用.

  • 请注意,在这种结构中,您将合成函数的元组版本,该函数本身在`foreach`*的每次迭代中从方法`f`*中解除. (3认同)

San*_*ozi 5

另一个很好的技巧广告问题3)(因为1和2已经被其他人回答)

val tuple = ("Mike", 40, "New York")
tuple match  {
  case (name, age, city) =>{
    println("Name: " + name)
    println("Age: " + age)
    println("City: " + city)
  }
}
Run Code Online (Sandbox Code Playgroud)

编辑:实际上它是模式匹配和案例类的一个特征,元组只是一个案例类的简单例子......