From 58da6137507863bbe4f462cc6171b3f6cdf889bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?F=E5=98=89=E9=98=B3?= Date: Thu, 3 Jan 2019 11:19:29 +0800 Subject: [PATCH] =?UTF-8?q?=E9=9A=90=E5=BC=8F=E8=BD=AC=E6=8D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../scala/top/fjy8018/scala/ImplicitApp.scala | 28 +++++++++++++++++++ .../scala/top/fjy8018/scala/RichFileApp.scala | 26 +++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 src/main/scala/top/fjy8018/scala/ImplicitApp.scala create mode 100644 src/main/scala/top/fjy8018/scala/RichFileApp.scala diff --git a/src/main/scala/top/fjy8018/scala/ImplicitApp.scala b/src/main/scala/top/fjy8018/scala/ImplicitApp.scala new file mode 100644 index 0000000..b8f749b --- /dev/null +++ b/src/main/scala/top/fjy8018/scala/ImplicitApp.scala @@ -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...") + } +} diff --git a/src/main/scala/top/fjy8018/scala/RichFileApp.scala b/src/main/scala/top/fjy8018/scala/RichFileApp.scala new file mode 100644 index 0000000..7ae9e6f --- /dev/null +++ b/src/main/scala/top/fjy8018/scala/RichFileApp.scala @@ -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 + } +}