1

I recently found out Scala does not allow multiple overloaded versions of the same method to have default parameters. I have a set of method overloads where an implicit parameter is needed if (and only if) one of the main parameters is specified. This would be the 'main' method:

def replies(after: Option[Post] = None, limit: Option[Int] = None)
           (implicit db: Instance, order: QueryOrdering[Post]): Stream[Post]

This fetches entries from a database with basic paging. If after is specified, only entries logically following it, according to order, should be retrieved. But I don't want to have to specify order for cases where after is not provided. But the following code is not allowed, as only a single overload can have default parameters:

def replies(limit: Option[Int] = None)
           (implicit db: Instance): Stream[Post]
  replies(limit = limit)(db, QueryOrdering.noOp)   

I could write down methods for all possible parameter combinations:

def replies()(implicit db: Instance)
def replies(after: Post)(implicit db: Instance, order: QueryOrdering[Post])
def replies(limit: Int)(implicit db: Instance)

But this is bothersome, and prone to combinatorial explosion for more than 2 parameters. Is there a better way to model this?

danielkza
  • 2,517
  • 1
  • 22
  • 20

1 Answers1

1

No one has said "magnet pattern" yet?

The magnet blog is here.

Everyone must be on a lunch break.

Then you control what implicits are available to package given combinations of args.

Sample answer.

Or tersely.

Community
  • 1
  • 1
som-snytt
  • 39,429
  • 2
  • 47
  • 129