Scala:Dynamic

Scala开篇(目录)

从Scala 2.10 开始,增加了Dynamic类型,所有直接或间接的继承自 Dynamic 的类,都可以实现。
Dynamic 继承自 Any,它的源代码中什么都没有,只有一句话。

trait Dynamic extends Any

按照官方的描述,Dynamic 是一个运行动态执行的 trait 标识,它没有成员,具体的实现由编译器嵌入,它可以动态的执行任意名字的方法或参数。这个怎么理解呢,我姑且认为它是动态产生方法和字段吧。
要想使用Dynamic ,需要打开编译器选项 -language:dynamics 或者 导入包:

import scala.language.dynamics

Dynamic 的操作都会经过下面四个方法

  1. selectDynamic:创建字段或方法
  2. updateDynamic:更新字段或方法
  3. applyDynamic:执行方法,可以带参数
  4. applyDynamicNamed:执行方法,参数可以指定名称

下面我们定义一个类,继承自Dynamic

class DynamicPerson extends Dynamic{
  def selectDynamic(key:String) = s"你要执行的是:$key"
}

先实现一个selectDynamic,看看它的使用
下面的代码,可以认为动态生成一个 Name方法,结果是一个字符串。

    val person = new DynamicPerson()
    person.Name       //定以后Name后,后面的代码中就可以访问Name了
    /**
    我们还可以增加其它的方法
    person.Age
    person.Address
    */
    println(person.Name)          // 输出结果 :"你要执行的是:Name"

那其实为了更清晰,我们更倾向于在DynamicPerson内部维护一个Map,里面可以保存属性和属性的值,或者是方法名和方法的引用,看下面的类:

import scala.language.dynamics
class DynamicPerson extends Dynamic{
  private val fields =mutable.HashMap.empty[String,Any].withDefault{ key => throw new NoSuchFieldError(key) }
  //获取key对应的value值
  def selectDynamic(key:String) = fields(key)
  //更新key对应的value值
  def updateDynamic(key: String)(args: Any): Unit ={
    fields(key) = args;
  }
}

下面是使用,用起来很方便,不用关心里面的Map,就好像定义和访问属性一样

    val person = new DynamicPerson()
    person.Age = 30
    person.Name = "Mike"
    //上面对 Age 和 Name 的赋值操作,就是通过 updateDynamic 完成的  
    println("%s年龄是%d".format(person.Name,person.Age))
    /**
    Mike年龄是30
    */

上面是属性的操作,那下面看看如何进行方法的操作,我们需要用到applyDynamic,定义下面的类

import scala.language.dynamics
class DynamicPerson extends Dynamic{
//定义一个方法类型 CallFun,它接收 Int 类型参数,并返回 String 类型 ,这个有点像 C# 中的 delegate 
  type CallFun = Int => String
  //Map对象,存放属性
  private val fields =mutable.HashMap.empty[String,Any].withDefault{ key => throw new NoSuchFieldError(key) }
  //Map对象,存放方法对象
  private val functions =mutable.HashMap.empty[String,CallFun].withDefault{ key => throw new NoSuchFieldError(key) }
  //选取对象
  def selectDynamic(key:String) = fields(key)
  /**
  更新key对应的value
  这里做了一个判断,如果key以call字符串开头,我们认为是args是CallFun类型
  */
  def updateDynamic(key: String)(args: Any): Unit ={
    args match {
      case x if key.startsWith("call") => functions(key) = x.asInstanceOf[CallFun]
      case _ => fields(key) = args
    }
  }
  //这个就是用来动态执行方法的
  def applyDynamic(key: String)(arg:Int) = {
    println(functions(key)(arg))
  }
}

使用

    val person = new DynamicPerson()
    //设置Name属性
    person.Name = "Mike"
    //定义一个 call 方法
    person.call = (age:Int) => s"${person.Name} 今年 $age 岁"
    //通过 applyDynamic 执行 call 方法 
    person.call(80)  //这句代码将打印出:"Mike 今年 80 岁"
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
"Scala: Guide for Data Science Professionals (Learning Path)" ASIN: B06XCJVY21, eISBN: 1787282856 | 2017 | True PDF | 1100 pages | 15 MB Scala will be a valuable tool to have on hand during your data science journey for everything from data cleaning to cutting-edge machine learning About This Book • Build data science and data engineering solutions with ease • An in-depth look at each stage of the data analysis process — from reading and collecting data to distributed analytics • Explore a broad variety of data processing, machine learning, and genetic algorithms through diagrams, mathematical formulations, and source code Who This Book Is For This learning path is perfect for those who are comfortable with Scala programming and now want to enter the field of data science. Some knowledge of statistics is expected. What You Will Learn • Transfer and filter tabular data to extract features for machine learning • Read, clean, transform, and write data to both SQL and NoSQL databases • Create Scala web applications that couple with JavaScript libraries such as D3 to create compelling interactive visualizations • Load data from HDFS and HIVE with ease • Run streaming and graph analytics in Spark for exploratory analysis • Bundle and scale up Spark jobs by deploying them into a variety of cluster managers • Build dynamic workflows for scientific computing • Leverage open source libraries to extract patterns from time series • Master probabilistic models for sequential data In Detail Scala is especially good for analyzing large sets of data as the scale of the task doesn't have any significant impact on performance. Scala's powerful functional libraries can interact with databases and build scalable frameworks — resulting in the creation of robust data pipelines. The first module introduces you to Scala libraries to ingest, store, manipulate, process, and visualize data. Using real world examples, you will learn how to design scalable architecture to process and model data — starting from simple concurrency constructs and progressing to actor systems and Apache Spark. After this, you will also learn how to build interactive visualizations with web frameworks. Once you have become familiar with all the tasks involved in data science, you will explore data analytics with Scala in the second module. You'll see how Scala can be used to make sense of data through easy to follow recipes. You will learn about Bokeh bindings for exploratory data analysis and quintessential machine learning with algorithms with Spark ML library. You'll get a sufficient understanding of Spark streaming, machine learning for streaming data, and Spark graphX. Armed with a firm understanding of data analysis, you will be ready to explore the most cutting-edge aspect of data science — machine learning. The final module teaches you the A to Z of machine learning with Scala. You'll explore Scala for dependency injections and implicits, which are used to write machine learning algorithms. You'll also explore machine learning topics such as clustering, dimentionality reduction, Naive Bayes, Regression models, SVMs, neural networks, and more. This learning path combines some of the best that Packt has to offer into one complete, curated package. It includes content from the following Packt products: • Scala for Data Science, Pascal Bugnion • Scala Data Analysis Cookbook, Arun Manivannan • Scala for Machine Learning, Patrick R. Nicolas Style and approach A complete package with all the information necessary to start building useful data engineering and data science solutions straight away. It contains a diverse set of recipes that cover the full spectrum of interesting data analysis tasks and will help you revolutionize your data analysis skills using Scala.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bdmh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值