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

How to use object-oriented programming in Scala

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article mainly explains "how to use object-oriented programming in Scala". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use object-oriented programming in Scala".

2 object-oriented programming

Scala uses functional programming in data processing, but it still uses an object-oriented model in the upper architecture organization, which is especially important for large applications.

Definition of class

The class is declared using the keyword class:

Class Counter {/ / the fields and methods of the class are defined here}

The first letter of the class name is recommended in Scala.

To define the fields of a class, use var/val, just like the definition of a variable.

To define the methods of a class, use the def keyword.

Let's define a complete class:

Class Woman {/ / define the field of the class val sex = "female" / / define the method of the class def usedToBeGirl (): Unit = {println ("A Woman used to be a girl.")}}

The return type of the method usedToBeGirl () is Unit, which means that it does not return any results, is a null value, and is expressed as ().

Scala's classes allow nested definitions

Methods of the class

Method invocation

If a method has no parameters, you can omit parentheses when defining it.

If parentheses are omitted in the definition of a method, you cannot call with parentheses; if you do not omit parentheses, you can call with parentheses or not.

For example:

Class MyFather {/ / define the field of the class val age = 40val sex = "male" / / define the method of the class def getAge (): Int = agedef getSex:String = sex}

Here the call to the getAge method:

/ / create an instance first val f = new MyFather// the following two calling methods can be declared with f.getAgef.getAge () / / getSex without parentheses, and cannot be called with parentheses f.getSex

The return value of the method

Method has a declared return type, then the return value is the value of the last execution statement in the body of the method

Method does not declare the return type, the scala compiler infers the return type based on the value of the last execution statement in the body of the method.

At this point, if you omit the equal sign and use curly braces, the scala compiler will infer the return value as Unit.

Method parameters

In Scala, the parameters of the method are immutable, and val is implicitly used for declaration, so you can neither use var or val when declaring the parameters, nor reassign the parameters in the method body.

You can explicitly name the parameter list when you call a method in scala.

Method overloading is allowed in scala

Nested definition of allowed methods in scala

Visibility of class members

In the scala class, the default visibility of all members is public and does not need to be qualified with the public keyword.

In addition to public, scala has the same visibility options as java: private and protected.

Private: visible to this class and nested classes

Protected: visible to this class and subclasses

Scala does not recommend setting all members as public properties, but it is recommended that they be set to private so that external members cannot access private fields directly. Therefore, like the getter and setter methods used in the java class, scala also provides methods to access and modify private fields.

Class Counter {/ / define a private field private var privateValue = 0 privateValue / provide methods for accessing and modifying privateValue def value = privateValuedef value_ = (newValue:Int) {if (newValue > 0) privateValue = newValue}}

Among them, value and value_ are paired.

Access the privateValue field:

/ / first instantiate an object val counter = new Counter// access privateValuecouner.value// modify privateValuecounter.value_ (3)

The method of modifying private fields on the can also omit the underscore _ (specified by scala syntax):

Counter.value (3)

This will be more intuitive.

Constructor

In scala, the definition body of the entire class is the class constructor, called the main constructor, and all statements outside the class methods will be executed during the construction process.

So how do you pass parameters to the constructor?

Scala specifies that the parameter list of the main constructor is listed in parentheses after the class name:

Class Counter (name:String) {privateval value = 0}

In addition to the primary constructor, a Scala class can have zero or more secondary constructors.

The first statement of each auxiliary constructor must be a call to the main constructor or a previously defined auxiliary constructor.

The auxiliary constructor is defined using this and is called in the form of this (parameter list).

Unlike the definition of the normal method, the parameters of the constructor can be defined using val or var. Scala automatically creates private fields for these parameters.

Using a parameter defined by val will only generate a read method for it because it is immutable and can only be read and not written.

Object singleton object

A singleton object in scala is equivalent to a static member in java.

The singleton object is defined using the object keyword:

Object Person {private var lastId = 0 {lastId + = 1 lastId}}

The singleton object is initialized the first time it is accessed.

There are two kinds of singleton objects: concomitant objects and isolated objects.

When a singleton object has a class with the same name, the singleton object is called the companion object of the class with the same name. Accordingly, this class of the same name is called the companion class of the singleton object. They can access each other's private members.

On the contrary, a singleton object without a class of the same name is called an isolated object. For example, the entry main method of a scala program is defined in an isolated object:

Object HelloWorld {/ / HelloWorld is an orphaned object def main (args []: array [string]) {println ("HelloWorld!")}}

Code files that contain concomitant class and object definitions cannot be executed directly with the ": load" command in REPL. They need to be compiled first and then executed with the scala command.

Apply method

The apply method has been used in the previous introduction:

Val strArr = Array ("hadoop", "spark", "flink")

You can see that an array object, strArr, is instantiated here, but it is not created with the new keyword, and the apply method is actually implicitly called. The whole process is that scala automatically calls an apply method in Array, the companion object of the Array class, and creates an Array object.

The apply method can also be defined in a class, such as the following class TestApply:

Class TestApply {def apply (param:String): Unit = {println ("apply method called" + param)}}

Execute the program in REPL mode:

First create a TestApply object named myObject. Then myObject ("Hello Apply") is executed, passing a parameter, and the result is that the apply method in the class is called automatically.

Scala > val myObject = new TestApply val myObject: TestApply = TestApply@3caf5c96scala > myObject ("Hello Apply") apply method called Hello Apply

However, my knowledge is still small, there is a doubt, change the name of the apply method to something else will automatically call this method?

As my experiments can prove, the answer is: no.

Rename the apply method in the TestApply class to helloApply and re-execute the program:

Scala >: load / usr/local/scala/mycode/testApply.scalaval args: Array [String] = Array () Loading / usr/local/scala/mycode/testApply.scala...class TestApplyscala > val myObject = new TestApplyval myObject: TestApply = TestApply@53da2aecscala > myObject ("Hello Apply") ^ error: TestApply does not take parametersscala > myObject.helloApply ("Hello Apply") apply method called Hello Apply

You can only explicitly call the helloApply method.

The apply method is defined in the accompanying object of the class (more commonly used)

If the constructor of a class is defined in the form of an apply method in the accompanying object of the class, the accompanying object of the class becomes a "factory", specializing in producing instances of the class, and the apply method is called a factory method.

In fact, the original purpose of apply method design is to maintain the consistency between objects and functions. In mathematics, functions are used in the form of functions (parameters), and functions are also objects in scala, so the method call of scala can omit the call to the method and use the method just like using a function.

Function (parameter) function. Method (parameter)

In scala, the rule for calling apply is that when you pass one or more parameters to a class instance or object name in parentheses, scala looks for a method named apply in the corresponding class or object, requires that the parameter list match the passed parameters, and then calls the apply method.

Update method

Update follows the same calling rules as the apply method, and the update method is used to reassign the object. For example, there is a update method in the companion object of the variable Map class, which can modify the value of a key.

Unapply method

The unupply method is used to deconstruct the object, and it is also called automatically.

The unapply method can be seen as a reverse operation of the apply method, which deconstructs the incoming parameters of the function from the constructor of a class.

Inherit abstract classes

If a class contains members (fields or methods) that are not implemented, it is an abstract class and is modified with the abstract keyword.

Abstract class Person {val name:Stringval age:Intdef getAge () def greeting () {println ("hello")}}

Abstract fields in an abstract class must declare a type. Abstract classes cannot be instantiated and can only be inherited by other classes as parent classes.

Unlike java, abstract methods in scala abstract classes do not need to be decorated with abstract.

Inheritance of class

Inheritance in scala, like java, supports only a single inheritance, that is, a subclass can have only one parent class. Inherited parent classes are represented by keywords using the extends keyword.

When defining subclasses, you need to be aware of the following:

The override keyword is optional when overloading abstract members of the parent class, and the override keyword is required when overloading non-abstract members of the parent class.

It is recommended that the abstract member of the overloaded parent class also use the keyword override. If the abstract member of the parent class is implemented in subsequent business, the member is a non-abstract member. Because the override keyword is required when reloading non-abstract members, if the subclass does not use the override keyword, a compilation error will occur, and the user will notice the change of the parent class in time.

Subclasses can only overload fields modified by val when overloaded. Var itself is mutable, and overloading does not make sense.

The main constructor of the subclass must call the primary or secondary constructor of the parent class.

If there is a parameter modified by val or var in the parent constructor, it is equivalent to the field of the class, so if the constructor parameter of the subclass contains a parameter with the same name as the constructor of the parent class, then the subclass constructor is equivalent to overloading the parent field, and the constructor parameter needs to be modified with override.

Class hierarchy of Scala

Type describes the subclasses of all reference types of the Null. The value is null, representing an empty object. The NothingNothing type is at the bottom of the class level of Scala; it is a subtype of any other type. AnyAny is the superclass of all other classes. The AnyRefAnyRef class is the base class of all reference classes (reference class) in Scala.

Nothing is mainly used for the return value type of exception handlers, so that no objects are returned after the exception is thrown, so exception handlers can be used more easily.

Option class

Scala uses the Option class to uniformly represent the value and non-value of an object. Option is an abstract class with a concrete class Some and an object Node. Some means value, and None means no value.

Parameterized type

Unlike parameterized types in scala, which are equivalent to generics in java, scala uses square brackets [] to define parameterized types.

Trait Trait

The idiosyncratic Trait in scala is equivalent to the interface in java. After a trait quilt class is implemented, it can be regarded as the parent class of this class, but unlike inheritance, the trait allows multiple implementations, that is, a subclass can be mixed with multiple attributes.

Attributes can be used to have both concrete and abstract methods, which is very similar to abstract classes.

Note:

If a trait does not explicitly indicate an inheritance relationship, then the trait inherits from AnyRef by default.

If a trait inherits from a parent class, it cannot pass parameters to the parent class constructor, which requires that the parent class inherited by the trait must have a no-parameter constructor.

To mix multiple attributes, you can use the with keyword (which can be used continuously):

Class Man extends Person with Boy {/ / Field and method implementation}

Traits cannot be instantiated

Pattern matching

Match statement

The most common pattern matching in scala is the match statement, which is similar to the switch statement in other languages.

Val grade = 90grade match {case 'A' = > println ("85-100") case 'B' = > println ("70-84") case 'C' = > println ("60-69") case _ = > println ("unqualified!")}

The last case uses an underscore "_" to represent other situations, which is equivalent to the default branch in java.

Case class

When defining a class, if you precede the class keyword with a case modifier, the class is a case class. Scala overloads a number of practical methods for the case class, including tiString,equals and hashcode methods. More importantly, scala automatically generates a companion object for each case class.

Bag

To resolve naming conflicts in programs, scala, like java, uses packages to organize programs in a hierarchical and modular manner.

There are two ways to put code in a specified package:

Declare using the package keyword at the top of the code file

Add a pair of curly braces to the package clause and put classes and objects in curly braces

Thank you for your reading, the above is the content of "how to use object-oriented programming in Scala". After the study of this article, I believe you have a deeper understanding of how to use object-oriented programming in Scala, 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