1. 程式人生 > 實用技巧 >scala 之 函式(二)

scala 之 函式(二)

一、柯里化

二、隱式引數

  1. implict只能修改最尾部的引數列表,應用於其全部引數
  2. Scala可自動傳遞正確型別的隱式值 、
  3. 通常與柯里化函式結合使用

例1:隱式變數

  implicit var k = 40      // 當傳參找不到引數y:Int時,發現implicit有k:Int,自動續上
//  implicit var k1 = 20    不能有第二個相同型別的implicit,衝突,所以隱式引數本質是型別匹配
  def abc(x:Int)(implicit y:Int): Int=x+y

  def main(args: Array[String]): Unit = {
    println(abc(
10)) }

例2-1:隱式方法之解決問題: 入參型別能匹配,出參不能匹配

  implicit  def string(st:String) = st.toInt;
  def bcd(x:Int)( y:String): Int=x+y  // 傳String型別卻可以計算,implicit 匹配上入參String出參Int的方法

  def main(args: Array[String]): Unit = {
    println(bcd(10)("60"))
  }

例2-2:隱式方法之解決問題: 出參型別能匹配,入參型別不能匹配

  implicit def cdf(str:String)= {
    str.replace(
"a","").size } def eee(c:Int): Unit ={ println(c) } def main(args: Array[String]): Unit = { eee("weraa"); // 型別匹配不上就找有沒有轉型別的implicit方法 }

例3:隱式類

  implicit class MyExtend(num :Int){
    var n:Int = num
    def sayhi = println(s"Hi,$n")
  }
  def main(args: Array[String]): Unit = {
    
234.sayhi // 有Int這個型別的隱式類,所以可以調方法 }