【问题标题】:Varargs to tuple in scala [duplicate]Varargs到scala中的元组[重复]
【发布时间】:2015-10-08 00:30:19
【问题描述】:

我是 scala 编程的新手,想编写一个函数,通过传入的参数返回一个元组实例。这就是我的意思:

def toTuple(strings : String*) = {
   //some code to create a tuple, if possible
   //the tuple should be consistent with the order the arguments were passed in
}

在scala中可以这样做吗?

【问题讨论】:

  • 查看链接的问题,但为了更好的帮助,你到底想实现什么/你背后的想法是什么?
  • @ElmarWeber 背后没有任何想法,我只是在学习 scala 并尝试不同的示例。
  • 由于历史原因,很难对 scala 元组进行抽象(这将在即将发布的版本中修复,但可能在未来几年内)。一般来说,如果你想通用地工作,最好使用 shapeless HLists。

标签: scala tuples


【解决方案1】:

问题在于这个函数的返回类型。应该是什么?任何?但这听起来不像是一个好的静态类型。我建议你使用类似的东西:

def toTuple(strings : String*): (String, String) = strings.toList match{
  case Nil => ("", "")
  case a :: Nil => (a, "")
  case a :: b :: xs => (a, b)
}

用法:

scala> toTuple(List("a"): _*)
res2: (String, String) = (a,"")

scala> toTuple(List("a", "b"): _*)
res3: (String, String) = (a,b)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-11
    • 1970-01-01
    • 2022-11-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-08
    • 1970-01-01
    • 2023-03-06
    相关资源
    最近更新 更多