Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do default method handling in Scala

Tags:

scala

I want to create a class that has an underlying map. I want to support operations such that the variables are resolved in the map. Normally we can have person("height") and have an apply method to resolve the key height in the map and return it.

I want to support fields to be resolved in this way. So person.height returns from the map. But the list of keys are not known before hand. So we cant enumerate all fields. Would it be possible to have a default handler of field resolution ?

like image 449
Arun Avatar asked Nov 20 '25 16:11

Arun


1 Answers

You probably want dynamic type:

http://www.scala-lang.org/api/current/index.html#scala.Dynamic

The SIP that lead to the addition of dynamic type in Scala 2.10: http://docs.scala-lang.org/sips/pending/type-dynamic.html

Here's a simple example that allow you to create objects with dynamic field resolution:

class MapBacked(initial: (String, Any)*) extends Dynamic {

  private val fields = mutable.HashMap[String, Any](initial: _*)

  // x.field translates to x.selectDynamic(field)
  def selectDynamic(field: String): Any = fields(field)

  // x.field = value translates to x.updateDynamic(field)(value)
  def updateDynamic(field: String)(arg: Any) = { fields(field) = arg }

}

Usage:

val x = new MapBacked("a" -> 1, "b" -> 2)
println(x.a) //prints 1
x.c = 42
println(x.c) //prints 42

You can also define dynamically resolved methods by defining an applyDynamic method.

like image 133
Marius Danila Avatar answered Nov 23 '25 07:11

Marius Danila



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!