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

 

  

相关文章:

  • 2021-08-14
  • 2021-12-10
猜你喜欢
  • 2022-12-23
  • 2021-11-09
  • 2021-07-08
  • 2020-02-15
  • 2021-05-17
  • 2021-06-11
相关资源
相似解决方案