steamer25
steamer25

Reputation: 9553

Scala primitives as reference types?

Does Scala provide a means of accessing primitives by reference (e.g., on the heap) out of the box? E.g., is there an idiomatic way of making the following code return 1?:

import scala.collection.mutable

val m = new mutable.HashMap[String, Int]
var x = m.getOrElseUpdate("foo", 0)
x += 1
m.get("foo")  // The map value should be 1 after the preceding update.

I expect I should be able to use a wrapper class like the following as the map's value type (thus storing pointers to the WrappedInts):

class WrappedInt(var theInt:Int)

...but I'm wondering if I'm missing a language or standard library feature.

Upvotes: 1

Views: 203

Answers (2)

Yuriy Tumakha
Yuriy Tumakha

Reputation: 1570

If your goal is to increment map values by key, than you can use some nicer solutions instead of wrapper.

val key = "foo"
val v = m.put(key, m.getOrElse(key, 0) + 1)

or another approach would be to set a default value 0 for the map:

val m2 = m.withDefault(_ => 0)
val v = m2.put(key, m2(key) + 1)

or add extension method updatedWith

implicit class MapExtensions[K, V](val map: Map[K, V]) extends AnyVal {
  def updatedWith(key: K, default: V)(f: V => V) = {
    map.put(key, f(map.getOrElse(key, default)))
  }
}

val m3 = m.updatedWith("foo", 0) { _ + 1 }

Upvotes: 0

pedrofurla
pedrofurla

Reputation: 12783

You can't do that with primitives or their non-primitives counter parts in Java nor Scala. Don't see any other way but use the WrappedInt.

Upvotes: 1

Related Questions