Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Scala: multiple overloaded alternatives of method

I have this code:

case class Sorting(field: String = "createdAt", order: 
 SortingOrder = SortingOrder.Desc)

object Sorting {
  sealed trait SortingOrder

  object SortingOrder {
    case object Desc extends SortingOrder
    case object Asc extends SortingOrder
  }

  def apply(field: Option[String], order: Option[SortingOrder], defaultSortField: String = "createdAt"): Sorting =
    Sorting(
      field.getOrElse(defaultSortField),
      order.getOrElse(SortingOrder.Desc)
    )

}

This gives error:

in object Sorting, multiple overloaded alternatives of method apply define default arguments.

Why am I missing here?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Scala compiler will generate default apply method in the companion object which will use your case class constructor parameters i.e. case class Sorting(field: String = "createdAt", order: SortingOrder = SortingOrder.Desc) which has default values. And then you have declared another apply method which has default parameters also and Scala disallows to have overloaded methods with default arguments.

So you need to remove default parameter either from case class (compiles) or from your custom apply method (compiles also) or handle custom default case manually by creating extra apply overload (compiles):

case class Sorting(field: String = "createdAt", order: SortingOrder = SortingOrder.Desc)

object Sorting {
  sealed trait SortingOrder

  object SortingOrder {
    case object Desc extends SortingOrder
    case object Asc extends SortingOrder
  }

  def apply(field: Option[String], order: Option[SortingOrder]): Sorting = apply(field, order, "createdAt")
  def apply(field: Option[String], order: Option[SortingOrder], defaultSortField: String): Sorting =
    Sorting(
      field.getOrElse(defaultSortField),
      order.getOrElse(SortingOrder.Desc)
    )
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading