Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the difference between object-oriented and functional programming between Java8 and Scala

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains the "Java8 and Scala object-oriented programming and functional programming what is the difference", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "what is the difference between Java8 and Scala object-oriented and functional programming?"

A mixture of object-oriented and functional programming: a comparison between Java 8 and Scala

Scala is a language that mixes object-oriented and functional programming. It is often seen as an alternative language to Java, and programmers want to use functional features in statically typed languages running on JVM while at the same time looking to maintain the consistency of the Java experience. Compared with Java, Scala provides more features, including a more complex type system, type inference, pattern matching, structure of a domain language, and so on. In addition, you can use any Java class library directly in your Scala code.

About Scala HelloWorld imperative Scalaobject Beer {def main (args: Array [String]) {var n: Int = 2 while (n System.out.println ("Hello" + n + "bottles of beer"));}}

Scala to realize

Object Beer {def main (args: Array [String]) {2 to 6 foreach {n = > println (s "Hello ${n} bottles of beer")} basic data structures: List, Set, Map, Tuple, Stream and Option create collections

It is very simple to create a collection in Scala

Val authorsToAge = Map ("Raoul"-> 23, "Mario"-> 40, "Alan"-> 53)

Add each element manually as in Java:

Map authorsToAge = new HashMap (); authorsToAge.put ("Raoul", 23); authorsToAge.put ("Mario", 40); authorsToAge.put ("Alan", 53)

Scala can easily create List (an one-way linked list) or Set (a collection without redundant data)

Val authors = List ("Raoul", "Mario", "Alan") val numbers = Set (1,1,2,3,5,8)

In Scala, the keyword val indicates that the variable is read-only and cannot be assigned (just like a variable declared as final in Java). The keyword var indicates that the variable is readable and writable.

A comparison between immutability and mutability

An important feature of Scala collections that we should keep in mind is that the collections we created earlier are read-only by default. This means that they cannot be modified from the beginning of creation.

Updating a Scala collection generates a new collection

Val numbers = Set (2,5,3); val newNumbers = numbers + 8 / / the operator + here adds 8 to Set, creates and returns a new Set object println (newNumbers) println (numbers)

There are several ways to create unmodifiable collections in Java. In the following code, the variable newNumbers is a read-only view of the collection Set object numbers:

Set numbers = new HashSet (); Set newNumbers = Collections.unmodifiableSet (numbers)

This means that you cannot add new elements to it by manipulating the variable newNumbers. However, the immutable collection is only a layer of encapsulation of the mutable set. By accessing the numbers variable directly, you can still add elements to it.

In contrast, an immutable set ensures that the set does not change at any time, no matter how many variables point to it at the same time.

Use the collection val fileLines = Source.fromFile ("data.txt") .getLines.toList () val linesLongUpper = fileLines.filter (l = > l.length () > 10) .map (l = > l.toUpperCase ()) tuple

Java currently does not support tuples

Scala provides a literal quantity called tuple

Val raoul = ("Raoul", "+ 44 887007007") val alan = ("Alan", "+ 44 883133700")

Scala supports tuples of any size

Val book = (2014, "Java 8 in Action", "Manning") val numbers = (42, 1337, 0, 3, 14)

You can access the elements in the tuple through the accessors (accessor) _ 1, _ 2 (a sequence starting from 1) based on their location, such as:

Println (book._1) println (numbers._4) Stream

Scala also provides the corresponding data structure, which calculates the data structure in a deferred manner, also known as Stream! However, Stream in Scala provides richer features, overshadowing Stream in Java. The Stream in Scala can record the values it has calculated, so previous elements can be accessed at any time.

In addition, Stream is indexed, so elements in Stream can be accessed through indexes like List. Note that this choice comes with overhead, because of the need to store these additional attributes, the Scala version of Stream memory is less efficient than the Stream in Java 8, because the Stream in Scala needs to be able to trace back previous elements, which means that previously accessed elements need to be "recorded" in memory (that is, cached).

Option

Optional of Java8

Public String getCarInsuranceName (Optional person, int minAge) {return person.filter (p-> p.getAge () > = minAge) .flatMap (Person::getCar) .flatMap (Car::getInsurance) .map (Insurance::getName) .orElse ("Unknown");}

In the Scala language, you can use Option to implement this function in a similar way to Optional:

Def getCarInsuranceName (person: Option [Person] MinAge: Int) = person.filter (_ .getAge () > = minAge) .flatMap (_ .getCar) .flatMap (_ .getInsurance) .map (_ .getName) .getOrElse ("Unknown") function def isJavaMentioned (tweet: String): Boolean = tweet.contains ("Java") def isShortTweet (tweet: String): Boolean = tweet.length ()

< 20 Scala语言中,你可以直接传递这两个方法给内嵌的filter,如下所示 val tweets = List( "I love the new features in Java 8", "How's it going?", "An SQL query walks into a bar, sees two tables and says 'Can I join you?'")tweets.filter(isJavaMentioned).foreach(println)tweets.filter(isShortTweet).foreach(println) 现在,让我们一起审视下内嵌方法filter的函数签名: def filter[T](p: (T) =>

Boolean): List [T] Anonymous functions and closures

Anonymous function

Val isLongTweet: String = > Boolean = (tweet: String) = > tweet.length () > 60val isLongTweet: String = > Boolean = new Function1 [String, Boolean] {def apply (tweet: String): Boolean = tweet.length () > 60} isLongTweet.apply ("A very short tweet")

If you use Java, you can use the following ways:

Function isLongTweet = (String s)-> s.length () > 60th Boolean long = isLongTweet.apply ("A very short tweet"); isLongTweet ("A very short tweet")

Closure

A closure is an instance of a function that has unrestricted access to non-local variables of the function. However, the Lambda expressions in Java 8 have certain limitations: they cannot modify the values of local variables in the function that defines the Lambda expression. These variables must be implicitly declared as final.

An anonymous function in Scala can get its own variable, but it is not the value of the variable that the variable currently points to.

Def main (args: Array [String]) {var count = 0 val inc = () = > count+=1 inc () println (count) inc () println (count)}

In Java, however, the following code encounters a compilation error because count is implicitly defined as final:

Public static void main (String [] args) {int count = 0; Runnable inc = ()-> count+=1;// error: count must be final or final inc.run () in effect; System.out.println (count); inc.run ();} Corialization

Example of Java

Static int multiply (int x, int y) {return x * y;} int r = multiply (2,10); static Function multiplyCurry (int x) {return (Integer y)-> x * y;} Stream.of (1,3,5,7) .map (multiplyCurry (2)) .forEach (System.out::println)

Scala provides a special syntax to automate this part of the work.

Def multiply (x: Int, y: Int) = x * yval r = multiply (2,10)

The Corey version of this function is as follows:

Def multiplyCurry (x: Int) (y: Int) = x * yval r = multiplyCurry (2) (10) val multiplyByTwo: Int = > Int = multiplyCurry (2) val r = multiplyByTwo (10) and trait's more concise Scala class

Because Scala is also a complete object-oriented language, you can create classes and instantiate them to generate objects.

Class Hello {def sayThankYou () {println ("Thanks for reading our book")}} val h = new Hello () h.sayThankYou ()

Getter method and setter method

Simply defining the Java class of the field list, you also need to declare a long list of getter methods, setter methods, and appropriate constructors. How troublesome it is!

Public class Student {private String name; private int id; public Student (String name) {this.name = name;} public String getName () {return name;} public void setName (String name) {this.name = name;} public int getId () {return id } public void setId (int id) {this.id = id;}}

Constructors, getter methods, and setter methods in the Scala language can all be generated implicitly, greatly reducing redundancy in your code:

Class Student (var name: String, var id: Int) val s = new Student ("Raoul", 1) println (s.name) s.id = 1337println (s.id) Scala's trait and Java8 interface comparison

Scala also provides another feature that is very helpful in abstracting objects, called trait. It is a substitute designed by Scala to implement interfaces in Java. You can define both abstract methods and methods with default implementations in trait. Trait also supports multiple inheritance of interfaces in Java, so you can think of them as similar to interfaces in Java 8, both of which support default methods. Trait can also contain fields such as abstract classes, which are not supported by the interface of Java 8.

Trait Sized {var size: Int = 0 def isEmpty () = size = = 0} class Empty extends Sized// A class println (new Empty (). IsEmpty ()) inherited from trait Sized / / printout true

You can create a Box class to dynamically decide which instance to choose to support the operations defined by trait Sized

Class Boxval b1 = new Box () with Sized / / build traitprintln (b1.isEmpty ()) / / printout trueval b2 = new Box () b2.isEmpty () / / compilation error: because the declaration of the Box class does not inherit Sized thank you for reading, this is the content of "what is the difference between object-oriented and functional programming between Java8 and Scala", after the study of this article I believe that you have a deeper understanding of the difference between Java8 and Scala in object-oriented and functional programming, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report