zoukankan      html  css  js  c++  java
  • 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

      

  • 相关阅读:
    Iterable,Iterator和forEach
    集合的线程安全性
    Servlet生命周期
    JavaWeb应用的生命周期
    将博客搬至CSDN
    (五)新类库的构件
    Python input和print函数
    python----调试
    Excel决定吃什么
    MATLAB—地图
  • 原文地址:https://www.cnblogs.com/AK47Sonic/p/7062289.html
Copyright © 2011-2022 走看看