package Scala12_5
//隐式转换的作用是什么?
//编译器自动滴,偷偷滴,把数据类型从A ——>B
//有可能会成功,也有可能失败
//implicit:隐式转换
object Scala12_05 {
// def main(args: Array[String]): Unit = {
//val i : Int = 1
把Int类型,转成Double类型
// val b:Double = i
//
//
// val d:Double = 1.2
// val j:Int = d
//
// }
// def getAge(): Double = {
// 19.5
// }
//
// def main(args: Array[String]): Unit = {
implicit 隐式转换
函数名字不重要
重要的是,参数类型和返回值类型
隐式函数:implicit修饰的函数
特点:1 自动被调用 2 函数名字不重要,重要的是,参数类型和返回值类型
// implicit def abs(d: Double): Int = {
// d.toInt
// }
//
// val i: Int = getAge()
// println(i)
// }
// 隐式值
// 函数的默认参数
// 函数的默认值:小花
// def sayName(implicit name: String = "小花"): Unit = {
// println(s"我叫:$name")
// }
// // 需求:更改函数参数的默认值(不传入这个值的时候,用到的值),不要写死
// // 步骤:
// // 1.定义函数的默认参数时,添加implicit
// // 2.需要修改这个默认值时,定义一个同类型的 隐式值: implicit修饰变量
implicit val xx:String = "小明明"
//
// def main(args: Array[String]): Unit = {
// sayName("小小")
// sayName
// sayName
//
// }
//开始你的代码....
implicit class StrongString(val str: String) {
def isPhone(): Boolean = {
val reg = "1[3-9]\\d{9}".r
reg.matches(str)
}
//验证是否身份证号
def isID: Boolean = {
val reg = "".r
reg.matches(str)
}
}
// 定义一个特殊的转换函数,把str====》StrongString 的对象
// implicit def xxxx(str: String): StrongString = {
// new StrongString(str)
// }
//
// def main(args: Array[String]): Unit = {
// val str:String = "13612345678"
// val str =
// println("136a".isPhone()) //==>False
// }
//
}
在SCala中隐式转换的理解与应用
小萌新~~~~2024-12-14 18:29
相关推荐
子兮曰1 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的子兮曰1 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议小羊没烦恼!1 天前
初探性能优化——2个月到4小时的性能提升爱勇宝1 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"胡写代码1 天前
别再前后端各写一套表单校验了伞伞悦读1 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__大勇前进1 天前
原生 PHP 还是 Laravel?小项目到底要不要上框架yuzhi_liu1 天前
我用 LangGraph4j 实现 Multi-Agent Supervisoralsmile1 天前
Node-RED 之外,国产规则引擎的新方案:基于标准语法,Go 先行实现大白801 天前
PHP 内存溢出排查思路:看懂报错日志,精准定位问题