scala學習筆記2 隱式轉換implicit

2021-07-08 12:49:55 字數 1915 閱讀 8423

一、 scala隱式轉換

乙個類例項a,有a方法而沒有b方法,需要將a轉換為提供b方法的類,稱為隱式轉換;

class richfile(val file: file) 

}

object context

object helloimplicit

}

隱式轉換在spark rdd的應用

rddtopairrddfunctions、rddtoasyncrddactions、rddtosequencefilerddfunctions等,這些是定義的隱身轉換,將rdd分別轉為pairrddfunctions(rdd)、asyncrddactions(rdd)等,提供更多的api

在spark rdd中的以上這些隱式轉換,在1.3之前是通過import sparkcontext._匯入的,之後直接移到了object rdd{}中(即rdd的伴生物件),使得編譯器能夠自動識別到,而不用像上列中那樣手動匯入:

將隱式轉化方法寫到對應類的伴生物件中,如下:

class fileimplicit(path: string) extends file(path) //需要指定繼承file哪個構造方法

object fileimplicit

println(new fileimplicit("d:\\webdata\\index.php").read())

二、 scala隱式引數和隱式轉換

隱式引數下的隱式轉換,將乙個型別t隱式轉為其他型別,例如implicit ordered : t => ordered[t]

**示例:

//將t型別隱式轉換為ordered[t],從而具有 > 方法

def bigger[t](a : t, b : t)(implicit ordered : t => ordered[t]) =

println(bigger(3,4))

三、 scala上下文界定的隱式轉換

[t :ordering]表示上下文界定的隱式轉換,變為ordering[t]

示例:  

class test[t : ordering](val first : t, val second : t) 

def bigger2() =

def bigger3() =

}

四、  scala隱式類

匯入隱式類,使得在當前的上下文作用域中的原始型別的得到增強:

object contexthelper

}implicit class filerich(file : file)

}

object implicitclass

}

五、 scala隱式物件

trait template[t] 

trait subtemplate[t] extends template[t]

object implicitobject

implicit object intadd extends subtemplate[int]

sum方法, 其中根據t的型別隱式轉換為對應的m

def sum[t](list :list[t])(implicit m : subtemplate[t]) : t =

def main(args: array[string]): unit =

}

scala學習筆記 隱式轉換

使用implicit關鍵字宣告的帶有單個引數的函式,會自動運用,將值從一種型別轉換為另一種型別 implicit def fun num double int num.toint 1var num int 3.5 輸出4.5注意 隱式轉化與函式名無關,只與引數型別和返回值型別有關 隱式函式可以有多個...

scala學習筆記 隱式轉換和隱式引數

隱式轉換 隱式引數 示例 示例1 隱式轉換 object mypredef class richfile val file file object richfile 示例2 隱式轉換 class cclass a c c class b c c def writebook unit object a...

scala 隱式轉換

defdisplay input string unit println input implicit deftypeconvertor input int string input.tostring implicit deftypeconvertor input boolean string if...