Home > Mobile >  Scala: multiple overloaded alternatives of method
Scala: multiple overloaded alternatives of method

Time:11-10

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?

CodePudding user response:

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)
    )
}
  • Related