Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>First off, as @pst pointed out, your example can be entirely implemented using static typing, it doesn't require dynamic typing.</p> <p>Secondly, if you want to program in a dynamically typed language, program in a dynamically typed language.</p> <p>That being said, you <em>can</em> actually do something like that in Scala. Here is a simplistic example:</p> <pre><code>class Dict[V](args: (String, V)*) extends Dynamic { import scala.collection.mutable.Map private val backingStore = Map[String, V](args:_*) def typed[T] = throw new UnsupportedOperationException() def applyDynamic(name: String)(args: Any*) = { val k = if (name.endsWith("_=")) name.dropRight(2) else name if (name.endsWith("_=")) backingStore(k) = args.first.asInstanceOf[V] backingStore.get(k) } override def toString() = "Dict(" + backingStore.mkString(", ") + ")" } object Dict { def apply[V](args: (String, V)*) = new Dict(args:_*) } val t1 = Dict[Any]() t1.bar_=("quux") val t2 = new Dict("foo" -&gt; "bar", "baz" -&gt; "quux") val t3 = Dict("foo" -&gt; "bar", "baz" -&gt; "quux") t1.bar // =&gt; Some(quux) t2.baz // =&gt; Some(quux) t3.baz // =&gt; Some(quux) </code></pre> <p>As you can see, you were pretty close, actually. Your main mistake was that <code>Dynamic</code> is a trait, not a class, so you can't instantiate it, you have to mix it in. And you obviously have to actually define what you want it to do, i.e. implement <code>typed</code> and <code>applyDynamic</code>.</p> <p>If you want <em>your</em> example to work, there are a couple of complications. In particular, you need something like a type-safe heterogenous map as a backing store. Also, there are some syntactic considerations. For example, <code>foo.bar = baz</code> is only translated into <code>foo.bar_=(baz)</code> if <code>foo.bar_=</code> exists, which it doesn't, because <code>foo</code> is a <code>Dynamic</code> object.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload