Scala类型推断错误

时间:2017-09-17 15:38:20

标签: scala generics type-inference scala-generics

我编写了一个组合的map-and-find函数,它将函数应用于Iterable并返回谓词为true的第一个映射结果:

edittext_searchname.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String str = edittext_searchname.getText().toString().toLowerCase(Locale.getDefault());
            adapter.filter(str);
        }
    });

问题是当我尝试按预期使用该函数时遇到了编译错误:

implicit class EnhancedIterable[A, B[X] <: Iterable[X]](it: B[A]) {

  def mapAndFind[B](f: A => B, p: B => Boolean): Option[B] = {
    var result: Option[B] = None
    for (value <- it if result.isEmpty) {
      val r = f(value)
      if (p(r))
        result = Some(r)
    }
    result
  }

}
  

类型不匹配,预期:(​​NotInferedB)=&gt;布尔值,实际:(没什么)=&gt;任何

如果我使用类型提示虽然编译得很好:

val names = Seq("Jose", "Chris", "Carlos", "Stephan")

names.mapAndFind(
  _.length,
  _ > 5 // Error
)

为什么类型names.mapAndFind( _.length, (len: Int) => len > 5 ) 未被B推断为Int

1 个答案:

答案 0 :(得分:1)

Scala中的类型推断在参数列表之间流动,而不是在它们内部。

你可以写:

implicit class EnhancedIterable[A, B[X] <: Iterable[X]](it: B[A]) {
  def mapAndFind[B](f: A => B)(p: B => Boolean): Option[B] = {
    var result: Option[B] = None
    for (value <- it if result.isEmpty) {
      val r = f(value)
      if (p(r)) result = Some(r)
    }
    result
  }
}

然后:

val names = Seq("Jose", "Chris", "Carlos", "Stephan")
names.mapAndFind(_.length)(_ > 5)

收率:

Some(6)