Similarities and Differences Between Scala and Java

download Similarities and Differences Between Scala and Java

of 4

description

Spark

Transcript of Similarities and Differences Between Scala and Java

Similarities and Differences between Scala and JavaSimilarities:1. Both are JVM based languages. Scala also produce bytecode. Scalac is Scala compiler like Javac for Java2. We can use Java code and Libraries in Scala and Scala code in java3. Major IDEs like Eclipse, Netbeans, and IntelliJ supports Scala4. Both are object oriented and Scala goes one step further and supports functional programming. (Java 8 supports functional programming)Differences:1. Scala drastically reduces number of lines from Java application by making clever use of type inference, treating everything as object, function passing and several other featuresJavapublic class Person{ private String firstName; private String lastName; String getFirstName() { return firstName; } void setFirstName(String firstName) { this.firstName = firstName; } String getLastName() { return lastName; } void setLastName(String lastName) { this.lastName = lastName; } int hashCode() .... boolean equals(Object o) { .... }}Scalacase class Person(firstName:String, lastName:String)

2. Scala supports immutable style of coding, which makes applying concurrency and parallelism easily3. Scala has built-in lazy evaluation, which allows to defer time consuming computation, until absolutely needed and you can do this by using a keyword called "lazy" as shown in below code// loading of image is really slow, so only do it if need to show imagelazyvalimages=getImages()//lazy keyword is used for lazy computation

if(viewProfile){showImages(images)}else(editProfile){showImages(images)showEditor()}else{// Do something without loading images.}

4. Code can be very nested supports defining function inside function, object and class5. Scala supports Operator Overloading6. Scala treats methods or functions as variables we can pass functions as arguments and we can return functions as result from functions7. Scala is Statically-typedMajor Differences:1. Lambda Expressions (also called anonymous functions in Scala)Javalist.sort((x,y)-> { int cmp = x.lastName.compareTo(y.lastName); return cmp!=0 ? cmp : x.firstName.compareTo(y.firstName)}Scalalist.sort((x,y) => { val cmp = x.lastName.compareTo(y.lastName) if (cmp!=0) cmp else x.firstName.compareTo(y.lastName)}

We can see that the code is really similar, but:Scalavar (maxFirstLen, maxSecondLen) = (0,0) list.foreach{ x => maxFirstLen = max(maxFirstLen, x.firstName.length) maxSecondLen = max(maxSecondLen, x.secondName.lenght)}

In java, it is impossible to modify the content the lambda expression has been called from.Thus, lambda expressions in Java are syntactic sugar over anonymous classes that have access to the final objects of a context only. But in Scala they are full-onclosuresthat have the full access to the context.2. Default methods in interfaces (Traits in Scala)Another feature borrowed by Java from Scala, is the default methods in interfaces. They correspond to traits in Scala in a way.Javainterface AsyncInput{ void onReceive(Acceptor acceptor) default void read(): Future { final CompletableFuture promise = new CompletableFuture(); onReceive( x -> promise.complete(x) ); return promise; }}Scalatrait AsyncInput[T]{ def onReceive(acceptor: T=>()): Unit def read: Future[T] = { Promise p = Promise[T]() onReceive(p.complete(_)) p.future }}

At first glance, they are the same, but:Scalatrait LoggedAsyncInput[T]{ override def onReceive(acceptor: T => ()) = super.onReceive(x => { println(sreceived:${x}) acceptor(x) })}

This is not possible in Java3. Stream Operations on CollectionsJavapeoples.stream().filter( x -> x.firstName.equals(Jon)).collect(Collectors.toList())Scalapeoples.filter(_.firstName == Jon)

In java, we need an additional interface Stream on collections4. The access to the SQL DatabasesScaladb.persons.filter(_.firstName === Jon).toList JavadbStream(em,Person.class).filter(x -> x.firstName.equals(Jon)).toList

5. Scala supports Macros it is a program code conversion during the compile timeobject Log { def apply(msg: String): Unit = macro applyImpl def applyImpl(c: Context)(msg: c.Expr[String]):c.Expr[Unit] = { import c.universe._ val tree = q"""if (Log.enabled) { Log.log(${msg}) } """ c.Expr[Unit](tree) }}

Log(message) expression will be replaced withif (Log.enabled) { Log.log(message)}

With the help of macros, we can generate the so-called boilerplate code. In Java boilerplate, we can also shorten the code by using reflections. But this will impose some restrictions in places that are critical to execution speed, as reflections are not free.(Scala-lang.org - Scala for java Programmars, n.d.)