代码之家  ›  专栏  ›  技术社区  ›  Josh Stone

Scala类型推断错误

  •  1
  • Josh Stone  · 技术社区  · 8 年前

    我编写了一个组合映射和查找函数,该函数将函数应用于Iterable,并返回谓词为true的第一个映射结果:

    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 // Error
    )
    

    如果我使用类型提示,尽管编译很好:

    names.mapAndFind(
      _.length,
      (len: Int) => len > 5
    )
    

    为什么是类型 B 不推断为 Int f ?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Yuval Itzchakov    8 年前

    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)
    
    推荐文章