Scala之隐式转换

来源:互联网 发布:交互设计经典书籍 知乎 编辑:程序博客网 时间:2024/04/30 10:09
package com.uplooking.bigdata.p4.generic
 
import java.io.{BufferedReader, File, FileReader}
 
import scala.io.Source
 
/**
  * Scala中的隐士转换
  */
object ImplicitOps {
  implicit def double2Int(d:Double) = d.toInt
 
  implicit def str2Int(str:String) = str.toInt
  def main(args: Array[String]): Unit = {
//    implictOps1
    implictOps2
 
  }
 
  implicit def file2RichFile(file:File) = new RichFile(file)
 
  class RichFile(val file:File) {
    def read = Source.fromFile(file).getLines().mkString
  }
 
  def implictOps2: Unit = {
 
//    val br:BufferedReader = new BufferedReader(new FileReader(""))
//    var line:String = null
//    while((line = br.readLine()) != null) {
//      println(line)
//    }
    val file = new File("E:\\test\\scala\\wordcount.txt")
    println(file.read)//---->调用了隐士转换
  }
 
  def implictOps1: Unit ={
    val x:Int = 3.5
    println("x====" + x)
    //
 
    val y:Int = "123456"
  }
 
}
0 0
原创粉丝点击