【发布时间】: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