scala 隐式转换

复制代码
package scala

object Demo28Implicit {
  def main(args: Array[String]): Unit = {
    /**
      * 显示类型转换
      *
      */


    val s: String = "1000"

    //显示转换
    val int: Int = s.toInt


    /**
      * 隐式转换
      * 1、隐式转换方法
      * 2、隐式转换变量
      * 3、隐式转换类
      *
      */


    def print(i: String): Unit = {
      println(i)
    }


    print("1000")

    print(1000.toString)

    /**
      * 隐式转换方法
      * 和方法名无关,和参数类型返回值类型有关
      * 可以隐式的将参数类型转换成返回值类型
      *
      * 在同一个作用域中只能有一个参数类型和返回值类型一样的隐式转换方法
      *
      */

    implicit def intToString(i: Int): String = {
      println("隐式转换方法被调用")
      i.toString
    }

    implicit def doubleToString1(i: Double): String = {
      println("隐式转换方法被调用")
      i.toString
    }

    print(1000)

    print(100)

    //在当前作用域中可以将Int 当成String 来用

    100.split("")


  }
}
复制代码
复制代码
package scala

import scala.io.Source

object Demo29Implicit {

  def main(args: Array[String]): Unit = {

    /**
      * 隐式转换参数
      *
      */


    def fun(str: String): String => Unit = {

      def f(per: String) = {
        println(str + "\t" + per)
      }

      f
    }


    fun("java")("后缀")


    //简写
    //函数柯里化
    def fun1(str: String)(per: String) = {
      println(str + "\t" + per)
    }

    fun1("scala")("后缀")


    /**
      * 隐式转换参数
      *
      * 方法调用的简写
      *
      */
    def fun2(str: String)(implicit per: String) = {
      println(str + "\t" + per)
    }

    //隐式转换变量
    implicit val str: String = "默认值"

    fun2("spark")
    fun2("scala")


    //y应用场景
    Source.fromFile("data/word.txt")


  }

}
复制代码
复制代码
package scala

import scala.io.Source

object Demo30Implicit {

  def main(args: Array[String]): Unit = {

    /**
      * 隐式转换类
      *
      */


    val student: List[String] = Source.fromFile("data/students.txt").getLines().toList


    val strings: List[String] = new FileReaad("data/students.txt").read()


    val list: List[String] = "data/students.txt".read()

    /**
      * 隐式转换
      * 动态给对象增加新的方法
      *
      */


  }

  /**
    * 隐式转换类
    * 可以将构造函数参数的类型隐式转换当前类
    *
    */
  implicit class FileReaad(path: String) {

    def read(): List[String] = {
      Source.fromFile(path).getLines().toList
    }

  }

}
复制代码

 

posted @   坤坤无敌  阅读(70)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
点击右上角即可分享
微信分享提示