用于元组功能的Scala返回类型

我想做一个scala函数,它返回一个scala元组。

我可以做一个这样的功能:

def foo = (1,"hello","world")

它将正常工作,但是现在我想告诉编译器我希望从函数返回什么,而不是使用内置的类型推断(毕竟,我不知道(1,"hello","world")是什么)。

Felix asked 2020-08-09T21:14:01Z
2个解决方案
68 votes
def foo : (Int, String, String) = (1, "Hello", "World")

编译器会将类型(Int, String, String)解释为Tuple3[Int, String, String]

oxbow_lakes answered 2020-08-09T21:14:06Z
3 votes

另外,如果您厌倦了编写(Int,String,String),则可以创建类型别名。

type HelloWorld = (Int,String,String)
...

def foo : HelloWorld = (1, "Hello", "World")
/// and even this is you want to make it more OOish
def bar : HelloWorld = HelloWorld(1, "Hello", "World")
WillD answered 2020-08-09T21:14:26Z
translate from https://stackoverflow.com:/questions/2743866/scala-return-type-for-tuple-functions