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 } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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 加持,客户体验更智能