【问题标题】:How to pass tuple for a HashMap variable's argument in scala?如何在scala中为HashMap变量的参数传递元组?
【发布时间】:2012-03-07 16:49:27
【问题描述】:

我想使用从方法返回的元组来创建一个新的 hashmap 项,但是当我这样写时它给了我错误

var data= HashMap[String,String]()
data.update(choose("name"))

def choose(a:String):(String,String)= return (a, "Pete")

如何使用 tuple 更新 hashmap?

Eclipse IDE 告诉我“方法更新的参数不足:(key: String, value: String)Unit。未指定值参数值。”并且不让我编译脚本。

【问题讨论】:

  • 因为data.update() 不接受元组。

标签: scala arguments return tuples


【解决方案1】:

代替

// update requires a separate parameters for key and value
data.update(choose("name")) // won't compile !

// the following will work
val (key,value) = choose("name")
data.update (key,value)

使用

data+=choose("name") // += takes (key,value) tuple as a parameter

【讨论】:

    【解决方案2】:

    这也有效:

    (data.update _).tupled(choose("name"))
    

    tupled 将需要多个参数的函数转换为需要参数元组的函数。

    在您的情况下,它不像 Vlad 的方法那样干净,但一般来说,当您有一个包含参数的元组时,可以使用 tupled

    val f = (a: String, b: String, c: String) => a + b + c
    val myargs = ("1", "2", "3")
    println(f.tupled(myargs)) // produces "123"
    

    【讨论】:

      猜你喜欢
      • 2018-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-12
      • 2011-06-12
      相关资源
      最近更新 更多