【问题标题】:Using lambda with generic type in Scala在 Scala 中使用具有泛型类型的 lambda
【发布时间】:2016-08-11 10:23:40
【问题描述】:

myFunc 的第二个参数是一个具有复杂参数的函数:

def myFunc(list : List[String],
           combine: (Map[String, ListBuffer[String]], String, String) => Unit) = {
    // body of myFunc is just a stub and doesn't matter
    val x = Map[String, ListBuffer[String]]()

    list.foreach ((e:String) => {
       val spl = e.split(" ")
       combine(x, spl(0), spl(1))
    })

    x
}

我需要将第二个参数传递给myFunc,因此它可以用于各种类型的A, B,而不是特定的String, ListBuffer[String]

def myFunc(list : List[A], combine: (Map[A, B], A, A) => Unit) = {

    val x = Map[A, B]()

    list.foreach(e => {          
        combine(x, e)
    })
}

如何声明和调用这样的构造?

【问题讨论】:

  • 需要指定A和B是类型参数,像这样:def myFunc[A, B](list: List[A], combine: (Map[A, B], A, A) => Unit)

标签: scala function generics lambda


【解决方案1】:

您可以执行以下操作,

def myFunc[A, B](list : List[A], combine: (Map[A, B], A, A) => Unit) = {
  val x = Map[A, B]()
  list.foreach (e => combine(x, e, e))
  x
}

像广告一样使用它

myFunc[String, Int](List("1","2","3"), (obj, k, v) => obj.put(k, v.toInt) ) 

【讨论】:

    【解决方案2】:

    您似乎希望概括正在使用的容器。你在找这样的东西吗?这里我们导入scala.language.higherKinds,这样我们就可以把Container,一个接受单个类型参数作为addPair的类型参数的一种。

    import scala.language.higherKinds
    
    def addPair[K, V, Container[_]](map: Map[K, Container[V]],
                                    addToContainer: (Container[V], V) => Container[V],
                                    emptyContainer: => Container[V],
                                    pair: (K, V)): Map[K, Container[V]] = {
        val (key, value) = pair
        val existingValues = map.getOrElse(key, emptyContainer)
        val newValues = addToContainer(existingValues, value)
    
        map + (key -> newValues)
    }
    

    【讨论】:

      猜你喜欢
      • 2015-07-09
      • 2020-03-27
      • 1970-01-01
      • 2019-02-02
      • 2018-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      相关资源
      最近更新 更多