AminMal
AminMal

Reputation: 3173

Is there any way to pimp a library in Scala 3 except implicits?

Is there a way to pimp a library in scala 3? (as implicits are going to be removed in scala 3) So is there any way to do that using "given and using"?

In scala 2 I would normally just do something like this:

implicit class ListOps[T](list: List[T]) {
  // just for the sake of example
  def myFlatMap(f: T => List[T]): List[T] = {
    if (this.list.tail.isEmpty) f(this.list.head)
    else f(this.list.head) ++ this.list.tail.myFlatMap(f)
  }
}

Upvotes: 1

Views: 157

Answers (1)

Dmytro Mitin
Dmytro Mitin

Reputation: 51683

In Scala 3 implicits are not removed, they just became given + using.

http://dotty.epfl.ch/docs/reference/contextual/relationship-implicits.html

You can "pimp a library" either (Scala 3 way) introducing extension method

extension [T](list: List[T]) def myFlatMap(f: T => List[T]): List[T] = {
  if (list.tail.isEmpty) f(list.head)
  else f(list.head) ++ list.tail.myFlatMap(f)
}

http://dotty.epfl.ch/docs/reference/contextual/extension-methods.html

or (emulating Scala 2 way) with a class + implicit conversion

import scala.language.implicitConversions
 
class ListOps[T](list: List[T]) {
  def myFlatMap(f: T => List[T]): List[T] = {
    if (this.list.tail.isEmpty) f(this.list.head)
    else f(this.list.head) ++ this.list.tail.myFlatMap(f)
  }
}

given [T] as Conversion[List[T], ListOps[T]] = ListOps(_)

http://dotty.epfl.ch/docs/reference/contextual/conversions.html

Actually,

implicit class ListOps[T](list: List[T]) {
  def myFlatMap(f: T => List[T]): List[T] = {
    if (this.list.tail.isEmpty) f(this.list.head)
    else f(this.list.head) ++ this.list.tail.myFlatMap(f)
  }
}

still works.

Upvotes: 4

Related Questions