简体   繁体   English

斯卡拉元组的地图列表

[英]Map List of tuples in Scala

I am getting compile error when trying to map list of tuples. 尝试映射元组列表时出现编译错误。 I have a method which return Future[List[(String, String)]] and I need to use those two set of String value to make a call to another method 我有一个返回Future[List[(String, String)]] ,我需要使用这两组String值来调用另一个方法

def myHelper(): Future[List[(String, String)]] = { ... }

def myWork() = {
  myHelper() map {
    case(firstVal, secondVal) => otherWork(firstVal, secondVal)
  }
} 

Error I am getting is 我得到的错误是

found: (T1, T2)
required: List[(String, String)]

Any suggestion? 有什么建议吗?

EDIT hmm .... I wasn't clear about my question. 编辑嗯...。我不清楚我的问题。 otherWork expect list of all result otherWork期望所有结果列表

def otherWork(firstVals: List[String], secondVals: List[Strong]) = { ... }

Depends on what you want to do. 取决于您要做什么。

Call otherWork on every tuple? 在每个元组上调用otherWork吗?

def myWork() = {
    myHelper().map(_.map {
        case (firstVal, secondVal) => otherWork(firstVal, secondVal)
    })
}

If otherWork: (String, String) => T , then myWork: () => Future[List[T]] . 如果otherWork: (String, String) => T ,则myWork: () => Future[List[T]]

If otherWork: (String, String) => Future[T] and you want to run them all and collect the results, then you can use something like 如果otherWork: (String, String) => Future[T]并且您想全部运行它们并收集结果,则可以使用类似

def myWork() = {
    myHelper() flatMap { list => Future.sequence(
        list map { case (firstVal, secondVal) =>
            otherWork(firstVal, secondVal)
        })
    }
}

With the question clarification, you want unzip . 澄清问题后,您需要unzip

def myWork() = {
    myHelper() map { list =>
        list.unzip match {
            case (firstVals, secondVals) => otherWork(firstVals, secondVals)
        }
    }
}

Federico Pellegatta's answer has a shorter form of writing this. Federico Pellegatta的答案写得短一些。

Let's implement the myWork function as: 让我们将myWork函数实现为:

def myWork = myHelper.map {
  helper => (otherWork _).tupled(helper.unzip)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM