Scala踩坑

1 implicit

(1) 隐式类型转换

用于自定义类型转换操作

1
2
3
4
5
6
7
8
9
10
11
// 定义隐式类型转换操作
implicit def z(a:String):Int = 2

val x :String = "1"

// 调用隐式类型转换函数
// 一般情况下,String不是Int的子类型,不能进行强制类型转换。
// 编译器会查找响应的隐式函数,满足入参为String,出参为Int
val y:Int = x // compiler will use z here like val y:Int=z(x)

println(y) // result 2 & no error!

(2) 隐式接收器转换(代理?)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Mahadi{
val haveCar:String ="BMW"
}

class Johnny{
val haveTv:String = "Sony"
}

val mahadi = new Mahadi
implicit def z(a:Mahadi):Johnny = new Johnny

// 编译器查找入参为Mahadi,出参为Johnny的隐式函数
mahadi.haveTv // compiler will use z here like new Johnny().haveTv
println(mahadi.haveTv)// result Sony & no error

(3) 隐式参数注入

1
2
3
4
5
6
7
8
9
10
11
12
13
def x(implicit a:Int)=a
implicit val z:Int =10

// 查找Int型隐式参数
x // compiler will use implicit like this x(z)
println(x) // will result 10 & no error.


def l(implicit b:Int)
def x(implicit a:Int)= l(a)

// 在x作用域类为l查找Int型隐式参数
def x(implicit a:Int)= l

Understanding implicit in Scala

Implicit Conversions and Parameters

2 Compilation Encoder error on spark 2.0

版本<= 1.6, Dataset上map直接在底层RDD上操作。

版本>1.6,需指定隐式参数Encoder

三种解决方案:

(1) import spark.implicits._

(2) map前调用.rdd转换为RDD

(3) 可以使用getAs[数据类型](下标)获取

3 reduceByKey 和groupByKey

Dataset中没有reduceByKey,可以使用groupByKey

Dataset转换为RDD后可以使用reduceByKey