当前位置: 首页 > news >正文

Scala的隐式转换

一:

1.隐式转换概述:

隐式转换与模式匹配都是scala中提供的比较强大的特性。

2.隐式转换的定义:

在实际编程中,要想把一个不匹配的类型赋值,需要先转换成匹配的类型。scala的隐式转换会自动将一种类型的数据转换成另一种类型。隐式转换就是scala自动转换。对于户编程而言不可见,不需要手动编写转换代码。

3.scala隐式转换声明

scala的隐式转换声明关键字为implicit

package test10object test10_4 {class StrongString(str: String) {def isPhone(str: String): Boolean = {val reg = "1[3-9]\\d{9}".rreg.matches(str)}def isEmail:Boolean={val reg="r"reg.matches(str)}}implicit def strongString(str:String):StrongString ={new StrongString(str)}def main(args: Array[String]): Unit = {val str: String = "13239612335"//需求:给字符串补充一个功能,isPhone。判断它是不是一个手机号码val rs = str.isPhone
//  val rs = (new StrongString(str)).isPhone
//      val rs = stringtoStrongString(str).isPhoneprintln(s"$str 的检查结果是:$rs")
}
}
package test10//隐式值
object test10_3 {//函数的默认参数//函数的默认参数:小花def sayName(implicit name:String="小花"):Unit ={println(s"我叫:$name")}//需求更 改函数的默认值(不传入这个值的时候,用到的值),不要写死//步骤://1.定义函数的默认参数时,添加implicit//2.需要修改这个默认值时,定义一个同类型的隐式值:implicit 修改变量implicit val xxx: String = "小明明"//  implicit val defaultValue:String="小明"def main(args: Array[String]): Unit = {sayName("无敌小旋风")sayNamesayName//小明}}
package test10
//潜规则:老代码不要改!!!可以加新代码
object test10_2 {
//小明def getAge():Double ={19.5}//implicit 隐式转换//函数名字不重要//重要的是:参数类型和返回值类型!!!//隐式函数:implicit修饰的函数//特点:1.自动被调用 2.函数名字不重要,重要的是,参数类型和返回值类型!implicit def abc(d:Double):Int ={d.toInt}//小花def main(args: Array[String]): Unit = {
//    val i :Int = doubleToInt(getAge())val i:Int = getAge()println(i)}}
package test10object test10_5 {class StrongString(val str:String){def isPhone():Boolean={val reg = "1[3-9]\\d{9}".rreg.matches(str)}//验证是否身份证号def isID:Boolean ={val reg ="".rreg.matches(str)}}//定义一个特殊的转换函数,把str ===> StrongString的对象implicit def xxxx(str:String):StrongString ={
//  println("偷偷调用implicit")new StrongString(str)
}def main(args: Array[String]): Unit = {println("136a".isPhone())}
}

http://www.lryc.cn/news/501351.html

相关文章:

  • 从视频编码的进化历程看技术革新
  • ECharts柱状图-阶梯瀑布图,附视频讲解与代码下载
  • 如何让Google快速收录你的页面?
  • 比例负载分配L(P);动态调整服务率:LDS
  • C++ ——— 类的 6 个默认成员函数之 构造函数
  • win11 恢复任务栏copilot图标, 亲测有效
  • 计算机网络-IPSec VPN工作原理
  • Tomcat项目本地部署
  • 开源数据同步中间件(Dbsyncer)简单玩一下 mysql to mysql 的增量,全量配置
  • 虚幻引擎开发命名规则
  • 解释强化学习中的batch, epoch, episode有什么区别与联系,分别有什么作用
  • MVC基础——市场管理系统(一)
  • 使用docker-compose安装Milvus向量数据库及Attu可视化连接工具
  • PostgreSQL函数中使用now()或current_timestamp的异同
  • 开发类似的同款小程序系统制作流程
  • bsp是板级支持包
  • P1784 数独 C语言(普遍超时写法)
  • 基于最新的Apache StreamPark搭建指南
  • 思科模拟器路由器的基本配置
  • vue3 computed watch 拓展reduce函数
  • MyBatis 中 SQL 片段复用
  • 【实操GPT-SoVits】声音克隆模型图文版教程
  • 用HTML和CSS实现3D圣诞树效果
  • Burp入门(10)-IP伪造插件
  • Mac软件推荐
  • 实验14 RNN的记忆能力和梯度爆炸实验
  • LeetCode面试题04 检查平衡性
  • oracle归档模式下的快速热备方法-适合小库
  • 【机器学习】【分子属性预测】——python读取.tar.gz文件(以OC22数据集为例)
  • Qt中禁止或管理任务栏关闭窗口的行为