Search code examples
scalascala-option

Why does Option extend Product?


I must be missing something, but I don't see the implementation of productElement and productArity of the Product trait in the Option class.

So two questions:

  1. Why would Option extend Product?
  2. How can it be that Option (or any of it's two subclasses) is not implementing the two methods?

Solution

  • When you generate an Option in scala you are actually generating a Some or a None which are both case classes/objects. The scala compiler does it's magic with case classes and generates Product methods for them.

    From Scala 2.10 Product.scala:

    /** Base trait for all products, which in the standard library include at
     *  least [[scala.Product1]] through [[scala.Product22]] and therefore also
     *  their subclasses [[scala.Tuple1]] through [[scala.Tuple22]].  In addition,
     *  all case classes implement `Product` with synthetically generated methods.
     *
     *  @author  Burak Emir
     *  @version 1.0
     *  @since   2.3
     */
    

    I hope that answers both your questions, compiler magic!