使用动态类型Dynamic Type
来源:互联网 发布:lol符文法师咋样知乎 编辑:程序博客网 时间:2024/05/16 01:48
scala作为一个严格的静态类型,它是支持动态类型的,当前他是属于实验性的,这里在实际的生产环境中是否是个good idea我也不晓得
类似宏我们得在编译器中开启这个功能
importscala.language.dynamics
使用也是比较简单的,我们可以用idea直接查看Dynamic的源码,而且里面也包含了四个方法的使用,我们只要实现对应的方法就可以达到动态语言的效果了
/* __ *\** ________ ___ / / ___ Scala API **** / __/ __// _ | / / / _ | (c) 2010-2013, LAMP/EPFL **** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ **** /____/\___/_/ |_/____/_/ | | **** |/ **\* */package scala/** A marker trait that enables dynamic invocations. Instances `x` of this * trait allow method invocations `x.meth(args)` for arbitrary method * names `meth` and argument lists `args` as well as field accesses * `x.field` for arbitrary field names `field`. * * If a call is not natively supported by `x` (i.e. if type checking * fails), it is rewritten according to the following rules: * * {{{ * foo.method("blah") ~~> foo.applyDynamic("method")("blah") * foo.method(x = "blah") ~~> foo.applyDynamicNamed("method")(("x", "blah")) * foo.method(x = 1, 2) ~~> foo.applyDynamicNamed("method")(("x", 1), ("", 2)) * foo.field ~~> foo.selectDynamic("field") * foo.varia = 10 ~~> foo.updateDynamic("varia")(10) * foo.arr(10) = 13 ~~> foo.selectDynamic("arr").update(10, 13) * foo.arr(10) ~~> foo.applyDynamic("arr")(10) * }}} * * As of Scala 2.10, defining direct or indirect subclasses of this trait * is only possible if the language feature `dynamics` is enabled. */trait Dynamic extends Any
1) applyDynamic
defapplyDynamic(methodName:String)(args:Any*)2) applyDynamicNamed与第一个不同的是可以拿到参数名称
3) 作为一个动态语言最常见的行为就是给对象赋予一个新的属性或者重新赋值,这里我们可以通过selectDynamic和updateDynamic方法做到
import scala.collection.mutableimport scala.language.dynamicsobject MagicBox extends Dynamic { private var box = mutable.Map[String, Any]() def updateDynamic(name: String)(value: Any) { box(name) = value } def selectDynamic(name: String) = box(name)}object Test extends App { MagicBox.banana = "banana" println(MagicBox.banana)}
0 0
- 使用动态类型Dynamic Type
- Kotlin-46.JavaScript动态类型(Dynamic Type)
- 1.3.3 - [defns.dynamic.type] - 【定义.动态.类型】
- 动态类型Dynamic
- Dynamic 动态类型 和双问号??的使用
- Dynamic 动态类型 和双问号??的使用
- 使用cxf动态创建客户端The type org.apache.cxf.endpoint.dynamic.DynamicClientFactory cannot be resolved.
- 1. objC 动态类型(dynamic typing)
- .Net 4.0 之 Dynamic 动态类型
- .NET 数据类型之动态类型(Dynamic)
- .Net 4.0 之 Dynamic 动态类型
- C#4.0 新特性 动态类型Dynamic
- .Net 4.0 之 Dynamic 动态类型
- C# 匿名对象(匿名类型)、var、动态类型 dynamic
- C# 匿名对象(匿名类型)、var、动态类型 dynamic
- 动态类型dynamic和动态语言运行时DLR
- dynamic基础类型/C#与动态脚本语言交互/dynamic自定义类型
- dynamic 类型不能跨程序集使用
- boost 字符串与文本处理 -> lexical_cast
- LabVIEW——Case结构
- Linux CentOS 6.4/6.5 配置VPN【图文|详细教程】
- react配置之浅谈
- 获取web服务器状态
- 使用动态类型Dynamic Type
- Tomcat下Server.xml配置详解
- 套接字(socket)基本知识与工作原理
- C#做服务使用Process启动外部程序没窗体
- CMOS与CCD的灵感度比较
- 中缀表达式转换为后缀表达式
- 移位溢注:告别依靠人品的偏移注入
- 真机调试iOS遇到的问题
- 引用外部js