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
}
}
}