Why is Scala disabling dynamic linking?

If I was writing a library, I would normally write Option like this:

abstract class Option[+A] {
  def map[B](f: A => B): Option[B]
}

case object None extends Option[Nothing] {
  override def map[B](f: Nothing => B): Option[B] = None
}

case class Some[+A](a: A) extends Option[A] {
  override def map[B](f: A => B): Option[B] = new Some(f(a))
}

      

Note the use of polymorphism for implementation map

. However, the actual implementation of the map is entirely within the Option class and looks like this:

def map[B](f: A => B): Option[B] =
    if (isEmpty) None else Some(f(this.get))

      

I argue that my implementation is cleaner (see the benefits of polymorphism elsewhere) and probably faster. In Either

cases like this, type comparison is used instead if

, reminding me of the operators switch

you see when C people use them in Java. Interestingly, a similar implementation Try

follows my OOP school. So I would suggest that a shorter solution was chosen in Option

. Are there any other reasons?

+3


source to share


1 answer


  • Option

    is an sealed

    abstract class, so it is not an object of OOP style polymorphism as you are not allowed to extend it with your class.

  • Most method implementations are method-based get

    and isEmpty

    only two of them are defined externally Option

    , keeping the sources for None

    and Some

    ridiculously small. Therefore, if you want to see how implemented flatMap

    or collect

    , you do not need to switch from one part of the source to another. I think this makes this source more readable.

  • These small functions are good candidates for inline JIT. The method to be sent can only be inlined through unsafe optimizations, which of course can rarely occur in a context where it is Option

    really needed. So I doubt your implementation is faster.

  • There is a lot said about Functional

    vs style OOP

    in the link provided by @mz and on the internet. Therefore, I will avoid this holy war.



+3


source







All Articles