Scala--隐式转换
来源:互联网 发布:数据透视表实例下载 编辑:程序博客网 时间:2024/05/22 06:05
说到隐式转换,不得不说关键字implicit。
》implicit
implicit的三个作用:
- 隐式参数【类似于缺省参数,区别是隐式参数的值可以在方法调用的前的上下文中指定】
- 隐式转换类型
- 隐式调用函数
隐式转换类型
下面是一个普通的函数,当输入参数为Int时,则会报错。
def printString(str) = println(str)
现在对str的内容进行扩展,也就是希望Int,Double等等类型都能够通过这个函数进行打印。
此时需要用到implicit,则可以满足我们的需求了。
implicit def intToString(input:Int) = input.toStringimplicit def booleanToString(input:Boolean) = if(input) "true" else "false"
再举一个例子:
简单说明:
从图片中可以看到,类Man和类SuperMan没有任何继承关系。此时假如想用Man类想拥有SuperMan类的“超能力”,则需要通过隐形转换,将Man类视作SuperMan类。
方法一 :
方法二 :
隐式调用函数
=====
隐式转换的应用
- 将当前的类型转换成预期类型,实际使用得并不多。
- 类型增强与扩展【重点!使用场景很多】
案例一:ArrayOps对Array的类型增强
一个典型案例是:Scala对Array对象进行的隐式转换。我们知道,Scala通过Predef声明了针对Array类型的两个隐式转换:一个是到ArrayOps的隐式转化,另一个是到WrappedArray的隐式转换。以前者为例,它为Array对象“添加”了大量的操作,这是通过隐式转换来”通明“的对一个类进行增强的典型案例!
案例二:Spark中PairRDDFunctions对RDD的类型增强
如果你看一下Spark中的RDD以及它的子类是没有groupByKey, reduceByKey以及join这一类基于key-value元组的操作的,但是在你使用RDD时,这些操作是实实在在存在的,Spark正是通过隐式转换将一个RDD转换成了PairRDDFunctions, 这个动作是这样发生的:
首先在RDD的伴随对象中声明了从RDD到PairRDDFunctions的隐式转换:
// The following implicit functions were in SparkContext before 1.3 and users had to // `import SparkContext._` to enable them. Now we move them here to make the compiler find // them automatically. However, we still keep the old functions in SparkContext for backward // compatibility and forward to the following functions directly. implicit def rddToPairRDDFunctions[K, V](rdd: RDD[(K, V)]) (implicit kt: ClassTag[K], vt: ClassTag[V], ord: Ordering[K] = null): PairRDDFunctions[K, V] = { new PairRDDFunctions(rdd) }
然后在SparkContext中import了RDD的所有东西,使隐式转换生效。
转载于:
http://blog.csdn.net/bluishglc/article/details/50866314
- scala-隐式转换
- scala 隐式转换
- Scala隐式转换
- Scala隐式转换
- scala隐式转换
- scala隐式转换
- scala 隐式转换
- scala隐式转换
- scala隐式转换
- scala隐式转换
- scala隐式转换
- Scala--隐式转换
- scala implicit 隐式转换
- scala implicit隐式转换
- Scala隐式转换实战
- Scala implicit隐式转换
- scala 隐式转换参数
- Scala之隐式转换
- assert的用法
- 条款16:成对使用new和delete时要采取相同形式
- 菜鸟遇到的一个问题的解决方案
- Caused by: java.lang.ClassNotFoundException: weblogic.jndi.WLInitialContextFactory
- 项目管理利器(Maven)——Pom.xml解析
- Scala--隐式转换
- 使用for循环打印9×9乘法表
- zimpha的bc出题录(当然是部分啦)
- 条款17:以独立语句将newed对象置入智能指针
- 重学数据结构 链表增删
- [codevs1135]选择客栈
- js小练习:利用getElementsByTagName方法、for循环、this指针、数组实现对多个相同元素value值的改变
- EhCache注解使用
- 用Windows自带工具给U盘4k对齐