Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I can not think of a reason to <em>really</em> need to add/create methods/properties dynamically at run-time <em>unless</em> dynamic identifiers are also allowed -and/or- a magical binding to an <em>external dynamic source</em> (JRuby or JSON are two good examples).</p> <p>Otherwise the example posted can be implemented entirely using the existing static typing in Scala via "anonymous" types and structural typing. Anyway, not saying that "dynamic" wouldn't be convenient (and as 0__ pointed out, is coming -- feel free to "go edge" ;-).</p> <p>Consider:</p> <pre><code>val dog = new { val name = "Rex" def speak = { "woof" } } val cat = new { val name = "Fluffy" def speak = { "meow" } } // Rock not shown here -- because it doesn't speak it won't compile // with the following unless it stubs in. In both cases it's an error: // the issue is when/where the error occurs. def test(animal: { val name: String; def speak: String }) = { animal.name + " is telling " + animal.speak } // However, we can take in the more general type { val name: String } and try to // invoke the possibly non-existent property, albeit in a hackish sort of way. // Unfortunately pattern matching does not work with structural types AFAIK :( val rock = new { val name = "Topaz" } def test2(animal: { val name: String }) = { animal.name + " is telling " + (try { animal.asInstanceOf[{ def speak: String }).speak } catch { case _ =&gt; "{very silently}" }) } test(dog) test(cat) // test(rock) -- no! will not compile (a good thing) test2(dog) test2(cat) test2(rock) </code></pre> <p>However, this method can quickly get cumbersome (to "add" a new attribute one would need to create a new type and copy over the current data into it) and is partially exploiting the simplicity of the example code. That is, it's not practically possible to create true "open" objects this way; in the case for "open" data a Map of sorts is likely a better/feasible approach in the current Scala (2.8) implementation.</p> <p>Happy coding.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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