问题
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