zoukankan      html  css  js  c++  java
  • Scala中使用implict 扩展现有类的方法

    Scala中implict的一种用法就是扩展现有类的方法,有点类似于.Net中的扩展方法(MS对扩展方法的介绍:扩展方法使你能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。)

    Scala中有两种方式做到方法的扩展,以扩展String为列:

    第一种(code:10-12,29):创建一个以implict修饰的新类并以String类型入参。在新的类型(代码中是mystring)中添加要扩展的方法(read2)

    第二种(code:3-5,9,28): 创建一个以implict修饰的方法并以String类型入参,方法中创建一个对象(代码中是RichString),该对象中包含要扩展的方法(read)

     Implict另一种用法是定义一个隐含的方法参数:code27行只传入一个参数,方法的另一个参数则取之code 8行。这种用发的前提是方法的参数必须有用implict修饰(code 17),才可以使用使用前面定义的隐含参数(code 8)

    代码和运行结果如下:

     1 object ImplictDemo {
     2 
     3   class RichString(val s:String){
     4     def read = (s + "_fun").mkString
     5   }
     6 
     7   object Context{
     8     implicit val impStr:String = "It is implicit"
     9     implicit def fun(s:String) = new RichString(s)
    10     implicit class myString(val s:String){
    11       def read2 = (s + "_class").mkString
    12     }
    13   }
    14 
    15 
    16   object Param{
    17     def print(content:String)(implicit prefix:String){
    18       println(prefix+":"+content)
    19     }
    20   }
    21 
    22   def main(args: Array[String]) {
    23     Param.print("A")("It is not implicit")
    24 
    25     import Context._
    26     import Context.fun
    27     Param.print("B")
    28     println(new String("").read)
    29     println(new String("").read2)
    30   }
    31 
    32 }

  • 相关阅读:
    SHA1 VS RSA: what's the difference between them?
    TLS Security
    TLS Handshake Protocol
    Building Cython code
    Getting started with JupyterLab
    Installing Cython
    【转贴】libcrypto.so.10丢失导致sshd无法运行解决方案
    [Typescript] Function Overloads
    [Typescript] Function Generics
    [Typescript] Discriminated (Tagged) Unions
  • 原文地址:https://www.cnblogs.com/1zhk/p/4736356.html
Copyright © 2011-2022 走看看