Scala的隐式对象和隐式类

1.隐式对象

Scala 复制代码
object Test1 {
  case class DatabaseConfig(drive:String,url:String)
  //隐式对象
  //格式:就是在对象前面加一个 implicit
  //作用:给函数当默认值
  implicit object MySqlConfig extends DatabaseConfig("sqlserver.jdbc","localhost:3306")

  //定义一个连接数据库的数据
  def getCon(implicit config: DatabaseConfig): Unit  =  {
    println(config)
  }
  def main(args: Array[String]): Unit = {
    println(MySqlConfig)
    getCon   //使用默认值
    getCon(DatabaseConfig("sqlite","localhost:80"))   //使用自己定义的值
  }
}

**2.**隐式类

Scala 复制代码
//隐式类 == 一个类 + 一个隐式转换函数
//格式:在class的前面,添加implicit
//要点:要有一个参数,就要待被转换的类型,返回的类型就是当前的类
object Test2 {
  implicit class X(s:String) {
    println("transform被调用了...")
    def testabc:Unit = {
      println("abc......",s)
    }
  }
//  def transform(s:String):X = {
//    println("transform被调用了...")
//    new X(s)
//  }
  def main(args: Array[String]): Unit = {
    "abcddd".testabc
  }
}
相关推荐
开开心心就好5 天前
用户推荐的文件解锁与强制操作工具
安全·智能手机·pdf·scala·音视频·symfony·1024程序员节
WL_Aurora6 天前
Scala核心编程(二):变量与数据类型详解
开发语言·scala
WL_Aurora7 天前
Scala核心编程(一):Scala语言概述与快速入门
spark·scala
o丁二黄o8 天前
语义版本控制:用Gemini镜像站实现合同条款的深度差异分析与风险追踪
javascript·kotlin·scala
与仪共舞11 天前
罗德与施瓦茨 NRP18S|三路二极管射频功率传感器
scala·数据库架构
howard200515 天前
1.8.3 掌握Scala类与对象 - Scala基本骨架方法
scala·基本骨架方法
howard200515 天前
1.9 掌握Scala抽象类与特质
scala·抽象类·特质
howard200516 天前
1.8.2 掌握Scala类与对象 - 单例对象与伴生对象
scala·伴生对象·单例对象
howard200518 天前
1.7.1 掌握Scala函数 - 声明Scala函数
scala·声明scala函数·显式声明·隐式声明
howard200520 天前
1.6.4 掌握Scala数据结构 - 元组
scala·元组