【问题标题】:Scala return type for tuple-functions元组函数的 Scala 返回类型
【发布时间】:2011-02-14 04:35:24
【问题描述】:

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

我可以做这样的功能:

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

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

【问题讨论】:

  • 好吧,伙计们...我责怪编译器没有给我任何有用的信息。我忘了放 = 号,因此我有很多错误。如果有人提出详尽的答案,我会接受它,正确的方法是: def foo:Tuple[Int,String,String] = (1,"hello","world")
  • Tuple3[...] 甚至,记得将项目的数量放在类名中(最多 22ish)

标签: function scala types return tuples


【解决方案1】:
def foo : (Int, String, String) = (1, "Hello", "World")

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

【讨论】:

    【解决方案2】:

    另外,如果你写累了,你可以创建一个类型别名 (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")
    

    【讨论】:

      猜你喜欢
      • 2011-07-27
      • 2019-08-12
      • 1970-01-01
      • 2014-05-29
      • 1970-01-01
      • 1970-01-01
      • 2018-02-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多