Did anyone already use this? I just came across this feature which is available since Scala 2.10 and I cannot justify a valid usecase to use this.
That is just the syntax. I understand that I can call methods that are not defined, but I still would need to write that piece of logic that needs to happen when I call that method. I'm simply failing to understand where this piece of logic would be written and how does Dynamic help me call that?
SCJP 1.4, SCWCD 1.4 - Hints for you, Certified Scrum Master
Did a rm -R / to find out that I lost my entire Linux installation!
I'm not sure I would have much need for this, given that one of the big advantages of Scala is supposed to be its static typing (otherwise why not use Clojure or Groovy?), but here's what Nilanjan Raychaudhuri says about this in Scala In Action:
Nilanjan Raychaudhuri wrote:Scala version 2.10 adds support for a Dynamic type. Using this feature you can dynamically add methods and fields to a type at runtime. This is very similar to the method_missing feature of Ruby and is quite useful if you’re building a domain-specific language (DSL). For example, Scala map is a collection of key value pairs and if you want to access the value associated with a key you can do something like the following:
Here someMap is a collection of two key value pairs and someMap.get("foo") will return 1. Using Dynamic we can easily change that so that we can access the keys as if they were part of a type:
The magic ingredient in this case is the selectDynamic method. (Scala methods are defined using the def keyword.) When the Scala compiler checks that foo is not part of the type it doesn’t give up immediately. If the type is a subtype of Dynamic it looks for the selectDynamic method and invokes it. If the method is not provided, you will get a compilation error.
I use dynamic types. In general they are used for interactions with an external (non-code) environment.
One use case is localization. See my simple messages library for an example. You may find usage examples under the test directory. This removes almost all boilerplate code used in the formatting.
Another set of use cases is data input from external formats. I have similar libraries for reading json, xml, SQL ResultSets, properties files (application configuration). Main purpose in the same as above: to reduce boilerplate code. I use code like this:
In that example there is a bunch of implicit and explicit conversions from DynamicTypeValue to any required type (Int, Long, String, Option[Something], Array[Something], etc...).
Same approach (dynamic with selectDynamic and set of conversions) is used for other mentioned readers like JSONInput.