【问题标题】:Missing parameter type for expanded function for List() in Scala 2.11Scala 2.11 中 List() 的扩展函数缺少参数类型
【发布时间】:2015-05-05 19:58:56
【问题描述】:

我有这个隐式类

object ListUtils {    
  /** adds methods to the List class */
  implicit class EnhancedList[A](val l: List[A]) extends AnyVal {

  /** splits this list into multiple sub-lists using the specified function --- splits after each element where the function is true */
  def splitWhere(f: A => Boolean): List[List[A]] = {
      @tailrec def splitAgain(list: List[A], result: List[List[A]]): List[List[A]] = list match {
        case Nil => result
        case _ => {
          if (list.exists(f(_))) {
            val (nextSubList, restOfOriginalList) = list.splitAt(list.indexWhere(f(_)) + 1)
            splitAgain(restOfOriginalList, nextSubList :: result)
          } else list :: result
        }
      }
      splitAgain(l, Nil).reverse
    }
  }
}

配合使用效果很好
val list = List("1", "2", "3", "x", "4", "5", "x", "6", "7", "8", "9", "x")
val splitList = list.splitWhere(_ == "x")

但是,在我将我的 scala 从 2.10.3 更新到 2.11.4 后,出现错误“缺少扩展函数的参数类型”的空列表会失败

scala> List().splitWhere(_ == 1)
<console>:14: error: missing parameter type for expanded function ((x$1)=> x$1.$eq$eq(1))
              List().splitWhere(_ == 1)

似乎类型推断不适用于 List[Nothing]。如果我使用它工作正常

List[Any]().splitWhere(_ == "x")

我想知道如何正确编写隐式函数来支持 List() 上的操作。提前致谢!

【问题讨论】:

  • EnhancedList[+A] 替换EnhancedList[A] 让我编译时没有类型注释(尽管有警告)。
  • 你为什么要故意写List().splitWhere(_ == 1)?这是输入Nil 的一种非常冗长的方式。

标签: scala


【解决方案1】:

您可以在其类型参数中声明您的implicit class EnhancedList[A] 协变,并让EnhancedList[Nothing] 视为EnhancedList[Any]。这样你就可以编译你的代码了,但是编译的时候我得到了以下警告:

警告:使用 `==' 比较 Nothing 和 String 类型的值会 总是产生错误 List().splitWhere(_ == "x")

所以可能会有问题。 (Fiddle)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-24
    • 1970-01-01
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    • 2017-12-12
    相关资源
    最近更新 更多