隐式转换

This commit is contained in:
2019-01-03 11:19:29 +08:00
parent 1c0f4a5628
commit 58da613750
2 changed files with 54 additions and 0 deletions

View File

@@ -0,0 +1,28 @@
package top.fjy8018.scala
/**
* 隐式转换
*
* F嘉阳
* 2019-01-03 10:59
*/
object ImplicitApp extends App {
// 定义隐式转换函数
implicit def man2superman(man: Man): Superman = new Superman(man.name)
val man = new Man("FJY")
man.fly()
}
class Man(val name: String) {
def eat(): Unit = {
printf(s"man[ $name ] eat...")
}
}
class Superman(val name: String) {
def fly(): Unit = {
printf(s"superman[ $name ] fly...")
}
}

View File

@@ -0,0 +1,26 @@
package top.fjy8018.scala
import java.io.File
import scala.io.{BufferedSource, Source}
/**
* 隐式转换样例2
*
* F嘉阳
* 2019-01-03 11:09
*/
object RichFileApp extends App {
// 目的在于为Java IO类增加读取文件内容方法
implicit def file2RichFile(file: File): RichFile = new RichFile(file)
val f = new File("tmp/hello.txt")
println(f.readConent)
}
class RichFile(file: File) {
def readConent = {
Source.fromFile(file.getPath).mkString
}
}