What's going on between Scala and Java

Source: Internet
Author: User

The relationship between Scala and Java, I think, can begin with a sentence: Scala comes from Java, but it's higher than Java.

Scala's designer Martin Odersky is a Java control, the man who designed the Javac and wrote the common code in the JDK. It can be said that the Java language itself is Martin Odersky one step at a glance to grow up. So Scala can say that it has a far-reaching relationship with Java in its roots.

Martin Odersky is still writing the Java meeting, and is determined to develop a goal: to make the writing process such a basic work become efficient, simple, and enjoyable! Therefore, Scala is an important milestone in the implementation of this goal.

So it can be said that Java is a professional outfit, Scala is casual wear.

Scala is concise and efficient. Java mature, stable.

But the ruler is long and the inches are short. Scala's simplicity and efficiency has its own scope of use: Scala is best suited for the field of algorithmic description, and Java is suitable for instruction programming.

Scala's unique two-trick: Functional programming, simple concurrent programming

1, Scala's unique functional programming.

The function is a one-class citizen in the Scala language.

The privilege of a class citizen is represented in: 1. Function can be passed, assigned value
Nested functions and anonymous functions in 2.scala
3.scala supports higher-order functions
4.scala support partial application (partial function)
5.scala Support Closures

For example:

1. Transitive
  

1def func (f: () = String) =println (f ())2Func (() = "HI")3 //Output:hi4         5def foo () = "OK"6 func (foo)7 //Output:ok8         9Val fun = (x:int) = =print (x)TenFun (2) One //Output:2

2. Nesting functions

1 def foo () {2    def Bar () {3         println ("HI")4        }  5    bar  //exec6}78// Output:hi        


Nested functions in the actual application of the scene is not many, one of the scenes is recursive function to the tail recursion!

1 def fun1 () {  2  ... .. 3    This      4 }  5  6def fun2 () {  7  .... 8    This 9 }ten// Two functions can be used in the following ways  (fun1). FUN2 ()

3. Anonymous functions

1 Lambda: Functional literal (function literal) 2 (x:int,y:int) + x +y3 parameter right-arrow function body 45 The above statement produces an anonymous function of type (INT, int) + int6 Note: There are 0 to 22 parameters for functions in Scala

4. Higher-order functions

1 The first: a function that uses a function to make a parameter. Eg:2 3def F2 (f: () =Unit) {f ()}4 5Def f1 () {println (1)}6 7 F2 (F1)8 9F2 (() = println ("HI"))//Incoming anonymous functionTen  One The second type: The result is a function function. Eg: A  -DEF HF (): int = int = x = x +1 -  theVal fun =HF -  -Fun (2)//Output:3


5. Function currying

1 When a function has more than one parameter2def sum (x:int,y:int) = x +y3 4 //after the parameters are scattered, two parameters are separated5def sum2 (X:int) (Y:int) = x +y6 7SUM2 (1) (2)//Output:38 9Scala> def first (x:int) = (y:int) and x+yTenFirst: (x:int) Int =Int One  AScala> First (1) -Res10:int = Int = <function1> -  theScala> Val Second=first (1) -Second:int = Int = <function1> -  -Scala> Second (2) +Res11:int = 3 -  + function Chain A Convert a function with multiple arguments to a function that has only one argument to execute at  -F (1) (2) (3) equivalent ((f (1)) (2)) (3) -  -Take the parameter 1 to perform FA (1) and then bring the parameter 2 to perform the FB (2) and then bring into the parameter 3 to execute the FC (3) finally get the result -  - What is the practical use of curry?  inControl abstraction, can change the writing style of code foo (res, () =>println (res)) foo (res) (() = println (res)) foo (res) {() =println (RES)} - implementing partial Application functions toscala> def log (time:java.util.date,msg:string) {println (time+msg)} + log: (Time:java.util.Date, msg:string) Unit -  thescala> val log2 = log (Newjava.util.date,_:string) *log2:string = Unit = <function1> $ Panax NotoginsengScala> log2 ("Test1") -Mon Sep 09 23:46:15CST 2013test1 the  +Scala> log2 ("Test2") AMon Sep 09 23:46:19CST 2013test2 the  +Scala> log2 ("Test3") -Mon Sep 23:46:22 CST 2013test3


6. Closures

1 anonymous inner class access to local variables in Java Yes, local variables must be declared final (similar to implementation of closures) 2 3 There's no such trouble in Scala: 4  5 scala> val more = 1 6 more:int = 1 7  8 scala> val addmore = (x:int) + x +  more 9 addmore:int = Int = <function1> scala> Addmore (10 ) res19:int = 11

(The above case section refers to the Internet published case and <programming in scala> section)

2. Scala's simple concurrent programming model

Scala's concurrent programming uses the Actor model, the Actor model (a popular term in the country called the Observer pattern).

In short, each participant broadcasts his or her state changes in some way, and other participants gain the status change before deciding whether to continue to participate.

Scala uses refined, functional programming to implement the Actor model, which enables single-core concurrency of the same JVM, multi-core concurrency for the same JVM, concurrency between multiple JVMs, and the implementation of IPC in some sense.

The typical actor programming model is as follows:

  

1 Scala notation 1:2 3 Importactors. Actor,actors. Actor._4 5 classA1extendsActor {6 7 def Act {8 React {9          CaseN:int=>println (Perfect (n))Ten         } One     } A } -  -N to n+10 foreach (i=>{  the(NewA1). Start!I -     } -)
1 val aa = Array.fill (2    3case          n:int=>  4         }5    }6)78 N to n+10 foreach (I=>AA (I-N)!)

The two ways of writing are only the same as declaring the class, one needs to explicitly call start, and the other does not need it.

The communication model between the different JVMs is as follows:

1 server-side:2 3Object ActorserverextendsApplication {4 5     Importactors. Actor, actors. Actor._, Actors.remote.RemoteActor6 7Actor.actor {//Create and start an actor8 9       //Current actor Listening Port:Ten  OneRemoteactor.alive (3000) A  -   -  the       //Register this actor on Port 3000, named Server1.  -  -       //The first parameter is the actor's identity, which starts with a single quote and is the Symbol in Scala, -  +       //The symbol amount is similar to a string, but symbol equality is based on string comparisons.  -  +       //Self refers to the current actor (note that this cannot be used here) A  atRemoteactor.register (' Server1, actor.self) -  -   -  -       //response after receiving a message -  in Loop { -  toactor.react { Casemsg = +  -println ("Server1 get:" +msg) the  *         } $ Panax Notoginseng       } -  the     } +  A } the  +   -  $ Client: $  -    -  theObject ActorclientextendsApplication { - Wuyi     Importactors. Actor, Actors.remote.Node, Actors.remote.RemoteActor the  - Actor.actor { Wu  -       //Get a node (Ip:port uniquely identifies a node) About  $       //Node is a case class, so you don't need a new -  -Val node = node ("127.0.0.1", 3000)  -  A   +  the       //Get the actor agent object corresponding to the node -  $Val remoteactor = remoteactor.select (node, ' Server1) the  the   the  the       //now Remoteactor is like a normal actor and can send a message to it!  -  inprintln ("--Begin to send Message")) the  theRemoteactor! "Actorclient's Message" About  theprintln ("--end")) the  the     }  +  -}

Other features of Scala, such as strong typing, are not described here.

The two points above should be the most fundamental feature between Scala and Java.

  

What's going on between Scala and Java

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.