Flink Scala API在泛型参数上起作用

Ale*_*rev 2 apache-flink

这是关于Flink Scala API"没有足够的论据"的后续问题.

我希望能够传递Flink的DataSet并使用它做一些事情,但数据集的参数是通用的.

这是我现在遇到的问题:

import org.apache.flink.api.scala.ExecutionEnvironment
import org.apache.flink.api.scala._
import scala.reflect.ClassTag

object TestFlink {

  def main(args: Array[String]) {
    val env = ExecutionEnvironment.getExecutionEnvironment
    val text = env.fromElements(
      "Who's there?",
      "I think I hear them. Stand, ho! Who's there?")

    val split = text.flatMap { _.toLowerCase.split("\\W+") filter { _.nonEmpty } }
    id(split).print()

    env.execute()
  }

  def id[K: ClassTag](ds: DataSet[K]): DataSet[K] = ds.map(r => r)
}
Run Code Online (Sandbox Code Playgroud)

我有这个错误ds.map(r => r):

Multiple markers at this line
    - not enough arguments for method map: (implicit evidence$256: org.apache.flink.api.common.typeinfo.TypeInformation[K], implicit 
     evidence$257: scala.reflect.ClassTag[K])org.apache.flink.api.scala.DataSet[K]. Unspecified value parameters evidence$256, evidence$257.
    - not enough arguments for method map: (implicit evidence$4: org.apache.flink.api.common.typeinfo.TypeInformation[K], implicit evidence
     $5: scala.reflect.ClassTag[K])org.apache.flink.api.scala.DataSet[K]. Unspecified value parameters evidence$4, evidence$5.
    - could not find implicit value for evidence parameter of type org.apache.flink.api.common.typeinfo.TypeInformation[K]
Run Code Online (Sandbox Code Playgroud)

当然,id这里的功能只是一个例子,我希望能够用它做一些更复杂的事情.

如何解决?

alj*_*cha 7

您还需要将TypeInformation作为K参数的上下文绑定,因此:

def id[K: ClassTag: TypeInformation](ds: DataSet[K]): DataSet[K] = ds.map(r => r)
Run Code Online (Sandbox Code Playgroud)

原因是,Flink分析您在程序中使用的类型,并为您使用的每种类型创建一个TypeInformation实例.如果要创建泛型操作,则需要通过添加上下文绑定来确保该类型的TypeInformation可用.这样,Scala编译器将确保在泛型函数的调用站点上有一个实例可用.