Skip to content

Instantly share code, notes, and snippets.

@DavidDudson
Last active October 5, 2017 22:00
Show Gist options
  • Save DavidDudson/135762c90c56c6780a2983a51bc3a453 to your computer and use it in GitHub Desktop.
Save DavidDudson/135762c90c56c6780a2983a51bc3a453 to your computer and use it in GitHub Desktop.
Trait based interning of case classes
import scala.collection.mutable
sealed trait InterningProvider[K, V] {
private[this] val cache =
mutable.WeakHashMap[K, V]()
protected def intern(args: (K))(builder: => V): V =
cache.getOrElseUpdate(args, builder)
}
abstract class Internable1[A, Z](f: (A) => Z) extends InterningProvider[(A), Z] {
def apply(a: A): Z =
intern(a)(f(a))
}
abstract class Internable2[A, B, Z](f: (A, B) => Z) extends InterningProvider[(A, B), Z] {
def apply(a: A, b: B): Z =
intern(a, b)(f(a,b))
}
// Example
final case class CaseClassWithOneElementInterned(s: String)
object CaseClassWithOneElementInterned
extends Internable1(new CaseClassWithOneElementInterned(_))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment