zoukankan      html  css  js  c++  java
  • 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这个类型的隐式类,所以可以调方法
      }
  • 相关阅读:
    UVa10779
    UVa10779
    C++ 内存管理学习笔记
    c++ 学习笔记
    AcWing 275 传纸条
    I
    Tree HDU6228
    Lpl and Energy-saving Lamps
    C
    Secret Poems
  • 原文地址:https://www.cnblogs.com/sabertobih/p/13666726.html
Copyright © 2011-2022 走看看