0
votes

I have this implicit class

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
    }
  }
}

It works fine with

val list = List("1", "2", "3", "x", "4", "5", "x", "6", "7", "8", "9", "x")
val splitList = list.splitWhere(_ == "x")

However, this fails for an empty list with error "missing parameter type for expanded function" after I update my scala from 2.10.3 to 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)

It seems that type inference doesn't work with List[Nothing]. It works fine if I use

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

I am wondering how I can write my implicit function properly to support operations on List(). Thanks in advance!

1
Replacing EnhancedList[A] with EnhancedList[+A] made me compile without type annotations (though with a warning).Gábor Bakos
Why would you purposefully write List().splitWhere(_ == 1) anyway? That's a very long-winded way of typing Nil.Michael Zajac

1 Answers

0
votes

You can declare your implicit class EnhancedList[A] covariant in its type parameter and let EnhancedList[Nothing] treat as EnhancedList[Any]. This way you can compile your code, but I got the following warning when it was compiled:

warning: comparing values of types Nothing and String using `==' will always yield false List().splitWhere(_ == "x")

So probably there might be problems. (Fiddle)