Scala implicit conversion and concurrent programming

Source: Internet
Author: User

1.Scala Implicit thorough explanation
implicit conversion implicit, which can be manually specified to convert an object of some type, or a class, into other types of classes or objects
Form: Implicit def function
Implicit functions, implicit arguments, implicit objects, implicit classes

implicit function : Refers to a function with implicit pre-modification
Scala uses the implicit conversion function's signature primarily as the input type, depending on the context, and uses an implicit conversion function when the program runs to automatically promote objects that are defined by the accepted implicit function parameter type to an implicitly converted object. Convert to another object return, and the task is converted back to its original type when it is completed. If the calling object does not have a method to invoke, Scala will try the last step before the error, make an implicit conversion, find the object with its implicit conversion, and then invoke the upgraded method after automatically upgrading to the implicitly converted class.
Syntax format:
Implicitdef function name (parameter) (The functional name is best defined as the original class to the implicitly converted class)

Here we define two classes, call their code method after the call to create a person object, the system error, because the class does not have this method.

class  person   (val name:string)   class  engineer   (Val name:string, Val salary:double)  { def  code{ println ( "Coding ..." )}}new  person ( "Spark" ). Code//error  def  Tocode (P:person) {p.code}//also error  implicit def  Persontoengineer (P:person): Engineer = {new  Engineer (P.name, 1000000 )} def  tocode (P:person) {P.code}  


Here we add the Tocode method to the Engineer class, define an implicit function, and define a Tocode method that Tocode method calls the person object, reporting the error in Java syntax because the class person does not have this method. But Scala will look for implicit functions, such as the implicit function we define, based on function signatures, mainly input parameters, find the Person2engineer method, and use this method to convert the person object to the engineer object before the error is made. The Engineer object is then found to have a Tocode method that directly calls its Tocode method, which prints the output. After running, the person object and the engineer type have no relationship.

It is important to note that although Scala does not require the return type to be stated when defining the implicit function, we should specify the return type, which will help the code to read.

In a large project, the interface is syntactically immutable, because it is contradictory to keep the interface stable, but at a later stage, the interface has to add something to extend. But Scala's implicit conversion can extend the interface. Also, it is implicit in code refactoring that is removed and incremented at any time.

 PackageCom.testImportScala.io.SourceImportJava.io.File class richerfile(val file:file){   defRead = Source.fromfile (File.getpath ()). Mkstring} class file_implicits(path:string) extends File(path)  Object file_implicits{ImplicitdefFile2richerfile (File:file) =NewRicherfile (file)//file-Richerfile} Object implicits_internals {    defMain (args:array[string]) {ValFile =NewFile_implicits ("Content.txt")//Current project directoryprintln (File.read)}}

Here we define a file_implicits class, note that it does not have a read method, in its associated object we define a conversion function file2richerfile, and then we define a Richerfile class, which contains the Read method. In the main function we first create a File_implicits object file, and then print the return value of its Read method. First, Scala will find a method in the class file_implicits read, not found, at this time do not error, but in the class of the half of the object to find an implicit conversion, the implicit conversion function, and input type, and then the input object is automatically converted to Richerfile, Then, with the Read method in the Richerfile class, Scala directly invokes the Read method of the file that has been implicitly converted, printing the result.

Implicit parameters :
The parameters injected by the actual assignment of the run-time context. It does not need to be assigned manually, and it automatically takes effect.

The actual mechanism: If an implicit parameter is defined, we do not need to provide this parameter manually at runtime, depending on the implicit value of the context (which can be either static or dynamic or configuration file, etc.), it is injected into the program according to the implicit value type and the implicit value itself. Let our program run properly. (The implicit value is found in two scopes, the current scope is implicit val,implicit Var, and the implicit value is found in the associated object of the implicit parameter type, which is generally the second range)


Here, we define a level class that represents a hierarchy, has defined a towork function, has two parameters, the first is the name of string, the second is the level of the implicit parameter type, and the function internally prints the rank of name and levels.
Then we define an implicit parameter level, and then we call the Towork method, but we just pass in a parameter, Scala prints out the results,

Here, Scala finds the implicit value level = new Level (8) from the context, and is automatically injected into the function towork as the second argument.

 Object context_implicits{ImplicitVal default: String ="Flink"//Implicit} Object Param{   defPrint (content:string) (implicit language:string) {println (language+":"+content)}} Object implicit_parameters {  defMain (args:array[string]) {Param.print ("Spark")("Scala")ImportContext_implicits._//Import all content under Context_implicitsParam.print ("Hadoop")  }}

Here, we define an implicit object, in the main method we import everything in it (mainly implicit parameters), then we can use the implicit parameters within him after importing.
Output Result:
Scala:spark
Flink:hadoop

an Implicit object
M is an implicit object passed in

Abstract  class Template[T]{defAdd (x:t,y:t): T}Abstract  class subtemplate[t] extends Template[t]{ defUnit:t} Object implicits_object{Implicit Object stringadd extends subtemplate[String]{Override defAdd (x:string,y:string) = x concat yOverride defUnit:string =""}implicit Object intadd extends subtemplate[Int]{Override defAdd (x:int,y:int) = X+yOverride defUnit:int =0}defSum[t] (xs:list[t]) (implicit m:subtemplate[t]): t=if(Xs.isempty) Ys.unitElseYs.add (Xs.head,sum (Xs.tail))//tail is the first element left outside of the elementprintln (SUM (List (1,2,3,4,5)) println (SUM (List) ("Scala","Spark","Kafka")))}}

First we define several abstract classes containing generics, the template is the parent class, and Subtempalte is a subclass, and this subclass has two sub-objects Stringadd and Intadd, the following is the SUM function defined in the main function, it is a function containing generics, Its first parameter is the XS with the generic list type, the second parameter is the implicit parameter m of the subtemplate type containing the generic, the function return value is a generic, first, the function first to determine whether the first parameter passed is empty, if it is empty, call the implicit parameter m, Because Scala can automatically type push to, so at run time, the generic t is a deterministic type, either int or string, but null, we call the implicit parameter m of the unit is different, int is 0, and string is "", So we define two implicit objects to process it, intadd implicitly class to make a copy of the unit, so that it is the 0,stringadd implicitly class to make a copy of the unit, so that the program can be executed normally. Similarly, the implicit object method makes a copy of the Add method and completes the sum operation.
Output Result:
15
Scalasparkkafka

Implicitly-Class

ImportScala.io.SourceImportJava.io.File Object context_helper{Implicit class fileenhancer(file:file){defRead = Source.fromfile (File.getpath). mkstring}implicit class OP(x:int){defADDSAP (Second:int) = x + Second}} Object implicit_class{defMain (args:array[string]) {ImportContext_helper._println (1.ADDSAP (2)) println (NewFile ("Context.txt"). Read)}}

Here we define two implicit class fileenhancer and op in the Context_helper object, in the main method, we go to all the contents of this object, and then println print, call 1.addSAP (2), first int class does not have this method, So Scala automatically converts to Richint, finds that this method is still not found, and then finds it in context, because it imports context_helper, so Scala finds the Implicit class op because the incoming type of its main constructor is exactly int, So he looked inside the OP, found the Addsap method, and the parameters were identical, so Scala would call this ADDSAP for processing, get the result 3, and the second print function would be similar.
Output Result:
3
Hi Scala

Find four methods or paths for implicit conversions :

First from the associated object of the current class,

Second, the implicit object and the implicit value are placed in an object, and then imported into it, will be found in this

Third, the implicit in the current scope is searched

The other is to import or make implicit writing when it is used.

2.Scala Concurrent Programming
In general, all the master in the program development, must be the concurrent programming of the message communication mode plus the wonderful use of caching.

Concurrent programming is the core of efficient CPU utilization. Using the actor in Scala. (Java multithreading is based on shared global variable locking mechanism, he must inevitably appear deadlock and state out of control, and in the distribution when there is a golden rule is not to use shared global variables, not to mention the lock mechanism. While the actor in Scala removes shared global variables, variables are private, and communication between actors is accomplished by sending messages. Avoiding a list of deadlock problems in traditional concurrent programming, Scala provides an actor-based framework, Akka.

Java thread disadvantage: Locking mechanism based on shared global variable brings deadlock, state out of control
Pros: Leverage multi-core concurrency, leveraging physical hardware
Actor removes the lock mechanism for shared global variables

import scala.actors.Actor//Actor样例class HiActor extends Actor{def act(){while(true){receive{case name: String => println(name)}}}}valnew HiActor()actor.start()

Actor! "Spark"//actor message,! Right is the content
Output: Spark

The actor here is similar to the Thread,actor Act method in Java, similar to the thread's Run method. There is a special syntax receive in the actor to receive messages (they are multi-threaded through the message mechanism), and then we do pattern matching, if a string type value, the value is passed to name, and then printed out.

Syntax format for sending messages: Actor name! The message content.

Use case class to implement message communication

Case   class Basic(name:string, age:int) Case   class Worker(name:string, age:int)  class basicactor extends Actor{defAct () { while(true) {receive{ CaseBasic (name, age) = println ("Basic Information:"+ name +":"+ age) CaseWorker (name, age) = println ("Worker Information:"+ name +":"+ Age)}}}

Input:
Val B = new Basicactor ()
B.start ()
B! Basic ("Scala", 13)
Output Basic information:scala:13
Input: B! Worker ("Spark", 16)
Output: Worker information:spark:16

Synchronous Message Syntax format: Actor name!? Message content

Receive asynchronous Message syntax format val variable name = actror name!! Message content (variable at some point in the future or get the value sent by the actor thread)

Scala implicit conversion and concurrent programming

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.