phadej
phadej

Reputation: 12123

Is there a naming convention for implicit classes?

For example in Objective-C, where class extensions are direct language construct, we do:

in filed named NSArray+FKBinarySearch.h:

@interface NSArray (FKBinarySearch)
// ...
@end

Do you name your extension classes like:

implicit class IndexedSeqBinarySearch[A](seq: IndexedSeq[A]) {
  // ...
}

For example scalaz calls makes extensions classes with suffix Ops: BooleanOps or even extending their own traits FoldableOps

Yet Ops feels too general, OTOH there are packages. Also Ops in scalaz case contains everything.

Upvotes: 10

Views: 1480

Answers (3)

lmm
lmm

Reputation: 17431

No, there's not really an established convention. @srgfed01 lists some approaches (other conventions I've seen in the wild: implicit conversions for X in an object called ImplicitX rather than Implicits, and PimpedX for the implicit class that wraps X), but you'll see all of these and more in extant scala libraries - sometimes multiple different conventions in the same library. There's nothing as well-established as the x2y style for implicit conversions, perhaps because implicit classes are a relatively new feature.

So pick a style you like, and be prepared to look for implicits under many different conventions in the libraries you use.

Upvotes: 3

user5102379
user5102379

Reputation: 1512

In Programming in Scala in "Chapter 21 · Implicit Conversions and Parameters" -> "Naming an implicit conversion." it is said:

Implicit conversions can have arbitrary names. The name of an implicit conversion matters only in two situations: if you want to write it explicitly in a method application, and for determining which implicit conversions are available at any place in the program.

In Programming Scala "Chapter 5: Implicits" -> "Wise Use of Implicits" it is said:

One way to improve implicits visibility is to adopt the practice of putting implicit values in a special package named implicits or an object named Implicits.

Using implicit class is like using implicit method, but in case of class its primary constructor is involved. And if you look at Scala implicit conversion methods results you can find something like:

  • wrapString(s: String): WrappedString
  • genericArrayOps[T](xs: Array[T]): ArrayOps[T]

In my opinion inside Implicits object for your implicit class name the following can be used:

  • xOps
  • RichX
  • WrappedX
  • AsX

You may choose any of them which is appropriate to your project conditions.

Upvotes: 10

som-snytt
som-snytt

Reputation: 39577

The standard lib has StringOps.

Someone on the mailing list turned me on to `absurdly descriptive backquoted identifiers` that avoid naming collisions among implicits.

OTOH, maybe you want to make it easy for a client to turn off the implicit by shadowing it.

Upvotes: 1

Related Questions