隐式转换
This commit is contained in:
28
src/main/scala/top/fjy8018/scala/ImplicitApp.scala
Normal file
28
src/main/scala/top/fjy8018/scala/ImplicitApp.scala
Normal 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...")
|
||||
}
|
||||
}
|
||||
26
src/main/scala/top/fjy8018/scala/RichFileApp.scala
Normal file
26
src/main/scala/top/fjy8018/scala/RichFileApp.scala
Normal 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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user