2014年02月21日 星期五 09:11
在C语言中,如果一个函数需要返回多个数据,有几种做法:
1,构造一个struct,将多个返回值封装为一个struct。
2,使用指针参数,使函数可以修改传入的参数变量。
在Scala中,就不需要这么费劲了,我们可以使用Tuple来返回任意个数据。
a tuple combines a fixed number of items together so that they can be passed around as a whole. Unlike an array or list, a tuple can hold objects with different types. Here is an example of a tuple holding an integer, a string, and the console:
Tuples save you the tedium of defining simplistic data-heavy classes. Even though defining a class is already easy, it does require a certain minimum effort, which sometimes serves no purpose. Tuples save you the effort of choosing a name for the class, choosing a scope to define the class in, and choosing names for the members of the class. If your class simply holds an integer and a string, there is no clarity added by defining a class named AnIntegerAndAString.
编程示例如下:
object S007_Tuples { def returnTuple: (Int, String) = { val name = "laomeng"; val id = 100 return (id, name) } def main(args: Array[String]): Unit = { val pair = (1, 2, 3, "mengguang"); println(pair._1); println(pair._4); println(pair.toString); val (x, y) = returnTuple println(x) println(y) } }
参考资料:
Zeuux © 2024
京ICP备05028076号