Im attempting to create a new operator 😕 on lists, which operates the same as :: except if the value if null, then the original list is returned. I have written the following, however it soon dawned that I didn’t really know what I was 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))
What you want is the enhance-my-library pattern. With this you can add a new method to
List. Here’s how that would look:So there’s a class
EnhancedListthat wrapsListwhere the new method?:is defined, and an implicit function that convertsListtoEnhancedListwhen?:is called. Note that you have to use?:instead of:?because Scala’s rules are such that an operator is right-associative if and only if it ends in a:.Here’s how it gets used: