※Function
類似 java 的 lambdaval showNum = () => 9
println(showNum()) // 9
val add = (x: Int) => x + 1
println(add(7))
val add2 = (x: Int, y: Int) => x + y
println(add2(1, 2)) // 3
※分別為 0~2 個參數
※傳 Function
val n = Seq(9, 7, 3)val func = (x: Int) => x * 2
println(n.map(func))
println(n.map((x: Int) => x * 2))
println(n.map((x) => x * 2))
println(n.map(x => x * 2))
println(n.map(_ * 2))
※以上 5 種寫法都是一樣的
※接收 Function
def plusOne1(list: List[Int]): List[Int] =list.map(n => n + 1)
def substractOne1(list: List[Int]): List[Int] =
list.map(n => n - 1)
def multyDouble1(list: List[Int]): List[Int] =
list.map(n => n * 2)
def plusOne2(list: List[Int]): List[Int] =
changeNumber(list, n => n + 1)
def substractOne2(list: List[Int]): List[Int] =
changeNumber(list, n => n - 1)
def multyDouble2(list: List[Int]): List[Int] =
changeNumber(list, n => n * 2)
/*private*/ def changeNumber(list: List[Int], calc: Int => Int): List[Int] =
list.map(calc)
val list = List(1,2,3);
println(plusOne1(list))
println(substractOne1(list))
println(multyDouble1(list))
println(changeNumber(list, n => n * 9))
※原本的 3 個 Xxx1 方法,回傳時,只有算法不同,所以可以提出變成公用的 changeNumber
※回傳 Function
def urlBuilder(ssl: Boolean = false, domainName: String): (String, Int) => String = {val protocol = if (ssl) "https://" else "http://"
(endpoint: String, pageNum: Int) => s"$protocol$domainName/$endpoint?page=$pageNum"
}
val getURL = urlBuilder(ssl = true, domainName = "www.google.com")
println(getURL("queryList", 10))
※這是修改官方的例子,回傳接收兩個參數,String 和 Int,並回傳 String
沒有留言:
張貼留言