Return first element of the tuple

浪子不回头ぞ 提交于 2020-07-09 16:55:48

问题


Suppose I create a function that adds two integers :

def addInt(a : Int, b: Int) : (Int, Int) = {
 | val x = a + b
 | (x,2)
 | }

I'm returning (result, 2) on purpose for the sake of this question.

Now I want to create a variable that returns only x.

val result = addInt(3,4) for example

result would return (7,2) but I only want it to return 7. How can I do this? (Without changing the code of the function obviously).


回答1:


val result = addInt(3,4)._1

And if you wanted the 2:

val the2 = addInt(3,4)._2



回答2:


Scala tuples have accessor methods for their elements called _1, _2, _3, and so on. So, to select the first element of the tuple, you would call _1:

someTuple._1

You can find the documentation for Scala's tuple class(es) in the Scala API documentation.

Alternatively, you can also use pattern matching.

val result      = addInt(3, 4)._1
val (result, _) = addInt(3, 4)


来源:https://stackoverflow.com/questions/46776254/return-first-element-of-the-tuple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!