[英]Type mismatch error on checking presence of element in a Set in Spark Scala API
I have defined following function written in Scala, for finding out whether particular type of nodes(Project,Filter) is contained in a given set or not:我定义了以下用 Scala 编写的函数,用于找出特定类型的节点(项目、过滤器)是否包含在给定的集合中:
private val operators = Set(Project.getClass,Filter.getClass)
def containsNode(plan: Seq[LogicalPlan]):Boolean=
{
for(p<- plan)
{
if(operators.contains(p.getClass))
true
}
false
}
When running the code I am getting the following error for the above function:运行代码时,我收到上述函数的以下错误:
Error:(182, 36) type mismatch;错误:(182, 36) 类型不匹配; found : Class[T(in value $anonfun)] where type T(in value $anonfun) <: org.apache.spark.sql.catalyst.plans.logical.LogicalPlan发现:Class[T(in value $anonfun)] 其中类型 T(in value $anonfun) <: org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
required: Class[_ >: T(in value operators) with T <: Serializable]要求:Class[_>: T(in value operators) with T <: Serializable]
if(operators .contains(p.getClass))
I thought p.getClass
would give same type of value that set operators
expect.我认为p.getClass
会提供与设置operators
期望的相同类型的值。 But it doesn't seem like it.但好像不是这样。 I am new to Scala and Spark, so I am not sure what exactly is going on here.我是 Scala 和 Spark 的新手,所以我不确定这里到底发生了什么。 Can anyone help me fix this error?谁能帮我解决这个错误?
In this case the problem is too precise type inference, you can fix it by explicitly saying operators
is a set of any classes:在这种情况下,问题是类型推断过于精确,您可以通过明确说明operators
是任何类的集合来解决它:
private val operators = Set[Class[_]](Project.getClass,Filter.getClass)
Though a second problem is that just using true
like that won't return it as you probably intend.尽管第二个问题是,像那样使用true
不会像您可能想要的那样返回它。 You can explicitly write return true
but better to use exists
which already contains the desired logic:您可以明确地写return true
但更好地使用已经包含所需逻辑的exists
:
def containsNode(plan: Seq[LogicalPlan]): Boolean =
plan.exists(p => operators.contains(p.getClass))
EDIT: a third possible problem is that Project
in Project.getClass
is not the class, but its companion object, you probably want classOf[Project]
instead.编辑:第三个可能的问题是Project.getClass
中的Project
不是类,而是它的伴随对象,你可能想要classOf[Project]
代替。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.