柚子快報(bào)邀請碼778899分享:大數(shù)據(jù)面試-Scala
柚子快報(bào)邀請碼778899分享:大數(shù)據(jù)面試-Scala
談?wù)剆cala的閉包、柯里化、高階函數(shù)
如果一個函數(shù),訪問到了它的外部(局部)變量的值,那么這個函數(shù)和他所處的環(huán)境,稱為閉包。 閉包在函數(shù)式編程中是一個重要的概念,廣泛用于高階函數(shù)、柯里化等技術(shù)中。
函數(shù)柯里化:把一個參數(shù)列表的多個參數(shù),變成多個參數(shù)列表; 函數(shù)柯里化,其實(shí)就是將復(fù)雜的參數(shù)邏輯變得簡單化,函數(shù)柯里化一定存在閉包。
高階函數(shù):1)函數(shù)可以作為值進(jìn)行傳遞 2)函數(shù)可以作為參數(shù)進(jìn)行傳遞 3)函數(shù)可以作為函數(shù)返回值返回
package com.scala.Function
object test_bibao {
def main(args: Array[String]): Unit = {
//普通函數(shù)
def makeMultiplier(factor:Int):Int={
return factor+1
}
println(makeMultiplier(1))
//閉包函數(shù):如果一個函數(shù),訪問到了它的外部(局部)變量的值,那么這個函數(shù)和他所處的環(huán)境,稱為閉包
def makeMultiplier1(factor: Int): Int=>Int = {
// 定義一個閉包函數(shù)
//val multiplier = (x: Int) => x * factor //匿名函數(shù)
def multiplier(x:Int):Int={
x * factor
}
// 返回閉包函數(shù)
multiplier
}
println(makeMultiplier1(1)(1))
//閉包函數(shù) + 匿名函數(shù)
def makeMultiplier2(factor: Int): Int => Int = {
// 定義一個閉包匿名函數(shù)
// val multiplier2=(x:Int)=>{x*factor}
val multiplier2 =(x:Int)=>x*factor
// 返回閉包函數(shù)
multiplier2
}
println(makeMultiplier2(1)(1))
//函數(shù)柯里化(柯里化一定會產(chǎn)生閉包)
def makeMultiplier3(factor: Int)(x: Int) = {
x * factor
}
println(makeMultiplier3(1)(2))
}
}
你對scala的伴生對象了解嗎?
伴生對象,與類名字相同,可以訪問類的私有屬性和方法 在 Scala 中,是沒有 static 這個東西的,但是它也為我們提供了單例模式的實(shí)現(xiàn)方法,那就是使用關(guān)鍵字 object。 Scala 中使用單例模式時(shí),除了定義的類之外,還要定義一個同名的 object 對象,它和類的區(qū)別是,object對象不能帶參數(shù)。 當(dāng)單例對象與某個類共享同一個名稱時(shí),他被稱作是這個類的伴生對象:companion object。你必須在同一個源文件里定義類和它的伴生對象。類被稱為是這個單例對象的伴生類:companion class。類和它的伴生對象可以互相訪問其私有成員。
/*單例對象實(shí)例*/
import java.io._
class Point(val xc: Int, val yc: Int) {
var x: Int = xc
var y: Int = yc
def move(dx: Int, dy: Int) {
x = x + dx
y = y + dy
}
}
object Test {
def main(args: Array[String]) {
val point = new Point(10, 20)
printPoint
def printPoint{
println ("x 的坐標(biāo)點(diǎn) : " + point.x);
println ("y 的坐標(biāo)點(diǎn) : " + point.y);
}
}
}
/*伴生對象實(shí)例*/
// 私有構(gòu)造方法
class Marker private(val color:String) {
println("創(chuàng)建" + this)
override def toString(): String = "顏色標(biāo)記:"+ color
}
// 伴生對象,與類名字相同,可以訪問類的私有屬性和方法
object Marker{
private val markers: Map[String, Marker] = Map(
"red" -> new Marker("red"),
"blue" -> new Marker("blue"),
"green" -> new Marker("green")
)
def apply(color:String) = {
if(markers.contains(color)) markers(color) else null
}
def getMarker(color:String) = {
if(markers.contains(color)) markers(color) else null
}
def main(args: Array[String]) {
println(Marker("red"))
// 單例函數(shù)調(diào)用,省略了.(點(diǎn))符號
println(Marker getMarker "blue")
}
}
柚子快報(bào)邀請碼778899分享:大數(shù)據(jù)面試-Scala
參考鏈接
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點(diǎn)和立場。
轉(zhuǎn)載請注明,如有侵權(quán),聯(lián)系刪除。