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