您的位置:首页 > 其它

Scala之隐式转换

2017-04-09 15:35 169 查看
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"

  }

 

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: