Practical uses of a Dynamic type in Scala

前端 未结 3 475
耶瑟儿~
耶瑟儿~ 2020-12-07 22:41

Besides integration with dynamic languages on the JVM, what are the other powerful uses of a Dynamic type in a statically typed language like Scala?

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-07 23:25

    You might also use it for syntactic sugar on maps:

    class DynamicMap[K, V] extends Dynamic {
      val self = scala.collection.mutable.Map[K, V]()
      def _select_(key: String) = self.apply(key)
      def _invoke_(key: String)(value: Any*) = 
        if (value.nonEmpty) self.update(key, value(0).asInstanceOf[V])
        else throw new IllegalArgumentException
    }
    
    val map = new DynamicMap[String, String]()
    
    map.foo("bar")  // adds key "foo" with value "bar"    
    map.foo         // returns "bar"
    

    To be honest this only saves you a couple of keystrokes from:

    val map = new Map[String, String]()
    map("foo") = "bar"
    map("foo")
    

提交回复
热议问题