scala-基礎之隱式轉換、隱式引數、隱式類-08
阿新 • • 發佈:2018-12-15
用IDEA建立maven專案後,在main中新建scala目錄,File->Project Structure->Modules設定scala目錄為sources,
再在Libraries中新增Scala SDK。
在scla中新建com.victor.scala包,新建Implict.scala
package com.victor.scala /** * Company: Huazhong University of science and technology * 華中科技大學電氣學院聚變與等離子體研究所 * Version: V1.0 * Author: Victor * Contact:
[email protected] 2018--2020 * Software: IntelliJ IDEA * File: Implict * Time: 2018/10/14 16:30 * Desc: **/ class Implict { } class Test{ } class RunTest(test: Test){ def run: Unit ={ println("RunTest-->test="+test) } } object Implict extends App{ //隱式轉換 implicit def test2RunTest(test: Test) = new RunTest(test) val test = new Test test.run //隱式引數 def testParam(implicit name:String): Unit ={ println("name="+name) } implicit val name ="Implicted......." testParam //明顯的指明引數 testParam("test wu ye .....") //隱式類 implicit class ADD(x:Int){ def add(a:Int):Int = a+x } println("2.add(23)="+2.add(23)) //the same to next line println("2.add(23)="+ADD(2).add(23)) }
=====================================================================
結果:
後續繼續更新。