Skip to content

no-argument extension method #5694

Closed
Closed
@drdozer

Description

@drdozer

Consider the typeclass:

trait Monoid[T] {
  def (lhs: T) mappend (rhs: T): T
  def mempty: T
}

Currently this allows us to write things like:

val x = 4 mappend 7
val y = implicitly[Monoid[Int]].mempty

The second operation, mempty, has to be invoked on an instance of the typeclass. This is ugly. We can work around this by introducing a syntax object and importing from it:

trait MonoidSyntax {
  def mempty[T](implicit T: Monoid[T]): T = T.mempty
}

Then as long as we have imported the members of a provider of MonoidSyntax into scope, we can write:

def y[Int] = mempty

However, this is the exact same boilerplate that the extension method magic got rid of. Is there a way to fix this?

trait Monoid[T] {
  def (lhs: T) mappend (rhs: T): T
  def () mempty: T
}

We could then say things like:

val x = 4 mappend 7
val y = mempty

without extra boilerplate either for the developer of Monoid or in the form of syntax imports within the invocation scope.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions