【问题标题】:Declare variable of type String* in scala [duplicate]在scala中声明String *类型的变量[重复]
【发布时间】:2018-10-03 20:18:30
【问题描述】:

有没有办法在scala中声明String*类型的变量?就像在可变数量的参数中一样?问题是,当我想测试一系列将String* 作为参数的方法并且不想只复制我在每个测试中传递的值时。我知道我可以更改函数以接收像 Array 或 Seq 这样的字符串集合,但我想知道是否有办法在不更改参数类型的情况下做到这一点

【问题讨论】:

  • 如果你有mySeq,即Seq[String],那么你可以将它传递给一个期望String*的方法,如下所示:foo(mySeq: _*)
  • 哇哦,好用!但为什么这行得通?当你在 foo() 中使用它时,你是在投射它吗?

标签: scala


【解决方案1】:

可变参数表示法:

def foo(ss :String*) = {
  //ss is Seq[String], you can ss.map(), ss.length, etc.
}

用法:

foo()
foo("this", "that")
foo("abc", "abd", "abx")

val someList = List("another" , "collection", "of", "strings")
foo(someList :_*) // turn a collection into individual varargs parameters

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2017-06-10
  • 2018-02-20
  • 1970-01-01
  • 1970-01-01
  • 2010-09-28
  • 2022-08-16
  • 1970-01-01
  • 2016-01-20
相关资源
最近更新 更多