Scala extending List class with coaledce preappend method

I'm trying to create a new operator :? in lists, which works the same as :: except if null, the original list is returned. I wrote the following, however it soon became clear that I really don't know what I am doing ....

object ImplicitList {
   implicit def extendIterator[T](i : List[T]) = new ListExtension(i)


 class ListExtension[T <: Any](i : List[T]) {
  def :?[B >: T] (x: B): List[B] = if (x != null) x :: i else i

 final case class :?[B](private val hd: B, private val tl: ListExtension[B]) extends ListExtension[B](tl.:?(hd))



source to share

1 answer

What you want is my library extension template. With that, you can add a new method to List

. This is how it will look:

class EnhancedList[T](self: List[T]) {
  def ?:(t: T) = 
    t match {
      case null => self
      case _ => t :: self
implicit def enhanceList[T](self: List[T]) = new EnhancedList(self)


So there is a class EnhancedList

that wraps List

where a new method is defined ?:

and an implicit function that converts List

to EnhancedList

when called ?:

. Note that you must use ?:

instead :?

because Scala's rules are that an operator is right-associative if and only if it ends in :


This is how it is used:

scala> val l = List("a","b","c")
l: List[java.lang.String] = List(a, b, c)

scala> null ?: l
res136: List[java.lang.String] = List(a, b, c)

scala> "d" ?: l
res137: List[java.lang.String] = List(d, a, b, c)




All Articles