Last active
October 5, 2017 22:00
-
-
Save DavidDudson/135762c90c56c6780a2983a51bc3a453 to your computer and use it in GitHub Desktop.
Trait based interning of case classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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