Invoke a method using a tuple as the parameter list [duplicate]

旧城冷巷雨未停 提交于 2019-12-19 14:57:49

问题


I wonder what is the best way to do this.

val foo = Some("a")
val bar = Some(2)

def baz(a: String, b: Int) = if((b % 2) == 0) Some(a+","+b) else None

(x zip y) flatMap baz //does not compile of course
(x zip y) flatMap { x => baz(x._1, x._2) } //ugly

I would presume that Odersky et al. have another trick up theirs sleeve to reduce the noise in this example.

So the question is how to fight the clutter here assuming you are not allowed to change the implementation of baz (e.g. def baz(a: (String Int))).


回答1:


This question has already been answered here: scala tuple unpacking

First, make foo to a function by partial application, then call tupled with your parameter list:

(foo _).tupled(myTuple)



回答2:


The most common way to cleanly unpack anything is with patterns or for-comprehensions:

for ((a,b) <- (x zip y); c <- baz(a,b)) yield(c)


来源:https://stackoverflow.com/questions/6322436/invoke-a-method-using-a-tuple-as-the-parameter-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!