首页 > 代码库 > Scala 学习笔记之implicit

Scala 学习笔记之implicit

implicit 分为隐式转换和隐式参数,下面例子展现了两种方式的用法:

package com.citi.scala

class Man(val name: String) {
  def talkWith(m: SuperMan) {
    println(s"Talk with ${m.name}")
  }

  def SayHello(msg: String)(implicit prefix: String) {
    println(prefix + ", " + msg)
  }

}
object Man {
  //  implicit def manToSuperMan(s: Man): SuperMan = {
  //    new SuperMan(s.name)
  //  }  
}

class SuperMan(val name: String) {
  def flyInSky {
    println("I can fly in the sky")
  }

}
object SuperMan {

}

object ImplicitLearning {
  implicit def manToSuperMan(s: Man): SuperMan = {
    new SuperMan(s.name)
  }

  implicit val prefix: String = "Hello"

  def main(args: Array[String]): Unit = {
    val m = new Man("Sky")
    //对象隐式转换
    m.flyInSky
    //方法参数隐式转换
    m.talkWith(m)

    m.SayHello("World")("See")
    //隐式参数
    m.SayHello("World")
  }
}

运行结果:

I can fly in the sky
Talk with Sky
Input, World
Hello, World

 

  

Scala 学习笔记之implicit