Why use tuples instead of objects?

后端 未结 10 1984
别那么骄傲
别那么骄傲 2020-12-24 05:29

The codebase where I work has an object called Pair where A and B are the types of the first and second values in the Pair. I find this object to be offensive, because it g

10条回答
  •  既然无缘
    2020-12-24 06:01

    Scala has tuple-valued types, all the way from 2-tuples (Pairs) up to tuples with 20+ elements. See First Steps to Scala (step 9):

    val pair = (99, "Luftballons")
    println(pair._1)
    println(pair._2)
    

    Tuples are useful if you need to bundle together values for some relatively ad hoc purpose. For example, if you have a function that needs to return two fairly unrelated objects, rather than create a new class to hold the two objects, you return a Pair from the function.

    I completely agree with other posters that tuples can be misused. If a tuple has any sort of semantics important to your application, you should use a proper class instead.

提交回复
热议问题