Ways to extend existing classes using Implict in Scala

Source: Internet
Author: User

One of the uses of implict in Scala is to extend existing classes in a way that is somewhat similar to. NET extension methods (MS for extension methods: extension methods enable you to "add" methods to existing types without having to create new derived types, recompile, or otherwise modify the original type.) )

There are two ways to extend the method in Scala to extend the string as a column:

The first (code:10-12,29): Creates a new class that is decorated with implict and takes the argument as a string type. Add a method to extend in the new type (mystring in the Code) (READ2)

The second (code:3-5,9,28): Creates a implict-decorated method and takes the argument as a string, creating an object in the method (richstring in the code) that contains the method to be extended (read)

Implict another usage is to define an implied method parameter: The Code27 line passes only one parameter, and the other parameter of the method takes the code 8 line. The precondition for this use is that the parameters of the method must be implict modified (code 17) to use the implied parameters defined previously (code 8).

The code and running results are as follows:

1 Object Implictdemo {2 3   classrichstring (Val s:string) {4def read = (s + "_fun"). mkstring5   }6 7 Object context{8Implicit val impstr:string = "It is implicit"9Implicit def fun (s:string) =Newrichstring (s)TenImplicitclassmyString (Val s:string) { Onedef read2 = (s + "_class"). mkstring A     } -   } -  the  - Object param{ - def print (content:string) (implicit prefix:string) { -println (prefix+ ":" +content) +     } -   } +  A def main (args:array[string]) { atParam.print ("A") ("It is not implicit") -  -     Importcontext._ -     ImportContext.fun -Param.print ("B") -printlnNewString (""). Read) inprintlnNewString (""). read2) -   } to  +}

Ways to extend existing classes using Implict in Scala

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.