Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type-safe equals macro?

Is there a type-safe equals === implementation for Scala that has zero overhead over ==? That is, unlike === in Scalaz and ScalaUtils, an implementation that uses a straight macro to perform the check?

I would like to use === in many places but these are hot-spots, so I don't want that to incur any extra runtime costs (like constructing type classes and such).

like image 962
0__ Avatar asked Nov 10 '22 04:11

0__


1 Answers

I think you can achieve it easily with machinist.

The README on GitHub gives exactly the === example:

import scala.{specialized => sp}

import machinist.DefaultOps

trait Eq[@sp A] {
  def eqv(lhs: A, rhs: A): Boolean
}

object Eq {
  implicit val intEq = new Eq[Int] {
    def eqv(lhs: Int, rhs: Int): Boolean = lhs == rhs
  }

  implicit class EqOps[A](x: A)(implicit ev: Eq[A]) {
    def ===(rhs: A): Boolean = macro DefaultOps.binop[A, Boolean]
  }
}

then you can use === with zero overhead (no extra allocations, no extra indirection) over ==


If you are looking for a out-of-the-box implementation, spire (from which machinist originated) provides one.

Also cats provides one.

They're both macro-based as they use machinist for the implementation.

like image 117
Gabriele Petronella Avatar answered Nov 15 '22 12:11

Gabriele Petronella