Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8576247
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T19:53:04+00:00 2026-06-11T19:53:04+00:00

I’m looking for a way to have classes that behave just like case classes,

  • 0

I’m looking for a way to have classes that behave just like case classes, but that are automatically hash consed.

One way to achieve this for integer lists would be:

import scala.collection.mutable.{Map=>MutableMap}

sealed abstract class List
class Cons(val head: Int, val tail: List) extends List
case object Nil extends List

object Cons {
  val cache : MutableMap[(Int,List),Cons] = MutableMap.empty
  def apply(head : Int, tail : List) = cache.getOrElse((head,tail), {
    val newCons = new Cons(head, tail)
    cache((head,tail)) = newCons
    newCons
  })
  def unapply(lst : List) : Option[(Int,List)] = {
    if (lst != null && lst.isInstanceOf[Cons]) {
      val asCons = lst.asInstanceOf[Cons]
      Some((asCons.head, asCons.tail))
    } else None
  }
}

And, for instance, while

scala> (5 :: 4 :: scala.Nil) eq (5 :: 4 :: scala.Nil)
resN: Boolean = false

we get

scala> Cons(5, Cons(4, Nil)) eq Cons(5, Cons(4, Nil))
resN: Boolean = true

Now what I’m looking for is a generic way to achieve this (or something very similar). Ideally, I don’t want to have to type much more than:

class Cons(val head : Int, val tail : List) extends List with HashConsed2[Int,List]

(or similar). Can someone come up with some type system voodoo to help me, or will I have to wait for the macro language to be available?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T19:53:05+00:00Added an answer on June 11, 2026 at 7:53 pm

    You can define a few InternableN[Arg1, Arg2, ..., ResultType] traits for N being the number of arguments to apply(): Internable1[A,Z], Internable2[A,B,Z], etc. These traits define the cache itself, the intern() method and the apply method we want to hijack.

    We’ll have to define a trait (or an abstract class) to assure your InternableN traits that there is indeed an apply method to be overriden, let’s call it Applyable.

    trait Applyable1[A, Z] {
      def apply(a: A): Z
    }
    trait Internable1[A, Z] extends Applyable1[A, Z] {
      private[this] val cache = WeakHashMap[(A), Z]()
      private[this] def intern(args: (A))(builder: => Z) = {
        cache.getOrElse(args, {
          val newObj = builder
          cache(args) = newObj
          newObj
        })
      }
      abstract override def apply(arg: A) = {
        println("Internable1: hijacking apply")
        intern(arg) { super.apply(arg) }
      }
    }
    

    The companion object of your class will have to be a mixin of a concrete class implementing ApplyableN with InternableN. It would not work to have apply directly defined in your companion object.

    // class with one apply arg 
    abstract class SomeClassCompanion extends Applyable1[Int, SomeClass] {
      def apply(value: Int): SomeClass = {
        println("original apply")
        new SomeClass(value)
      }
    }
    class SomeClass(val value: Int)
    object SomeClass extends SomeClassCompanion with Internable1[Int, SomeClass]
    

    One good thing about this is that the original apply need not be modified to cater for interning. It only creates instances and is only called when they need to be created.

    The whole thing can (and should) also be defined for classes with more than one argument. For the two-argument case:

    trait Applyable2[A, B, Z] {
      def apply(a: A, b: B): Z
    }
    trait Internable2[A, B, Z] extends Applyable2[A, B, Z] {
      private[this] val cache = WeakHashMap[(A, B), Z]()
      private[this] def intern(args: (A, B))(builder: => Z) = {
        cache.getOrElse(args, {
          val newObj = builder
          cache(args) = newObj
          newObj
        })
      }
      abstract override def apply(a: A, b: B) = {
        println("Internable2: hijacking apply")
        intern((a, b)) { super.apply(a, b) }
      }
    }
    
    // class with two apply arg 
    abstract class AnotherClassCompanion extends Applyable2[String, String, AnotherClass] {
      def apply(one: String, two: String): AnotherClass = {
        println("original apply")
        new AnotherClass(one, two)
      }
    }
    class AnotherClass(val one: String, val two: String)
    object AnotherClass extends AnotherClassCompanion with Internable2[String, String, AnotherClass]
    

    The interaction shows that the Internables’ apply method executes prior to the original apply() which gets executed only if needed.

    scala> import SomeClass._
    import SomeClass._
    
    scala> SomeClass(1)
    Internable1: hijacking apply
    original apply
    res0: SomeClass = SomeClass@2e239525
    
    scala> import AnotherClass._
    import AnotherClass._
    
    scala> AnotherClass("earthling", "greetings")
    Internable2: hijacking apply
    original apply
    res1: AnotherClass = AnotherClass@329b5c95
    
    scala> AnotherClass("earthling", "greetings")
    Internable2: hijacking apply
    res2: AnotherClass = AnotherClass@329b5c95
    

    I chose to use a WeakHashMap so that the interning cache does not prevent garbage collection of interned instances once they’re no longer referenced elsewhere.

    Code neatly available as a Github gist.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I have a French site that I want to parse, but am running into
I have a jquery bug and I've been looking for hours now, I can't
I have just tried to save a simple *.rtf file with some websites and
I've got a string that has curly quotes in it. I'd like to replace
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
This could be a duplicate question, but I have no idea what search terms
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
I would like to count the length of a string with PHP. The string
link Im having trouble converting the html entites into html characters, (&# 8217;) i

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.