斯卡拉类型不匹配。找到类型,需要_ $ 1

时间:2014-08-03 21:52:20

标签: scala

我收到的编译错误是我不明白的。下面的代码产生以下错误:

错误:类型不匹配;  found:oldEntity.type(底层类型为com.mycompany.address.AddressEntity)  必需: $ 1     this.esDocsForAddressEntity.filter( .shouldTriggerRefresh(oldEntity,newEntity))。map(_。esDocName)

object AddressToEsDocMapper {


  private val esDocsForAddressEntity = List[EsDocRefreshTrigger[_]](new PartyAddressRefreshTrigger())


  def findEsDocsForUpdate(oldEntity : AddressEntity, newEntity : AddressEntity) : List[String] = {
    this.esDocsForAddressEntity.filter(_.shouldTriggerRefresh(oldEntity, newEntity)).map(_.esDocName)
  }


  private class PartyAddressRefreshTrigger extends EsDocRefreshTrigger[AddressEntity] {

    val esDocName = "PartyAddress"

    override def shouldTriggerRefresh(oldEntity : AddressEntity, newEntity : AddressEntity) : Boolean = {
      oldEntity.addressLine2 != newEntity.addressLine2 || 
      oldEntity.addressLine3 != newEntity.addressLine3 || 
      oldEntity.addressLine1 != newEntity.addressLine1
    }

  }

}

1 个答案:

答案 0 :(得分:4)

您没有提供所有代码,但可能是因为您在esDocsForAddressEntity的定义中使用了通配符。在解决表达式中的类型参数时,它无法将oldEntity与任意EsDocRefreshTrigger的类型arg相关联。

$1名称只是编译器的内部或临时名称。

不是一个很好的例子,但是:

scala> val ss = List[Option[_]](Some("a"))
ss: List[Option[_]] = List(Some(a))

scala> ss filter (_.isDefined)
res2: List[Option[_]] = List(Some(a))

scala> ss filter (_.get.length > 0)
<console>:9: error: value length is not a member of _$1
              ss filter (_.get.length > 0)
                               ^

蛮力:

scala> class Foo { type A ; def foo(a: A) = 42 }
defined class Foo

scala> class Bar extends Foo { type A = Int }
defined class Bar

scala> class Baz extends Foo { type A = String }
defined class Baz

scala> val foos = List[Foo](new Bar, new Baz)
foos: List[Foo] = List(Bar@55cb6996, Baz@1807e3f6)

scala> foos map { case bar: Bar => bar foo 3 ; case baz: Baz => baz foo "three" }
res1: List[Int] = List(42, 42)

scala> def f(x: Foo)(a: x.A) = x foo a
f: (x: Foo)(a: x.A)Int

或者使用foo方法提供Bars和Bazes的类型类。