[Scala] Scala object-oriented programming

1. class

(1) Define class 1. Define classes, including field s and methods

class HelloWorld {
  private var name = "leo"
  def sayHello() { print("Hello, " + name) }  
  def getName = name
}
copy

2. Create the object of the class and call its method

val helloWorld = new HelloWorld
helloWorld.sayHello() 
print(helloWorld.getName)
copy

The method can also be called without parentheses. If the method is defined without parentheses, the method cannot be called with parentheses (2) getter and setter Define a var field without private. At this time, when scala generates a JVM oriented class, it will be defined as the name field of private and provide public getter and setter methods. If private is used to modify the field, the generated getter and setter will also be private. If val field is defined, only getter methods will be generated. If you do not want to generate setter and getter methods, declare the field as private[this]. In other words, for the attribute declared with var, Scala will program this field as private and private when compiling, but will provide public getter and setter methods provided externally. In this way, there is no need to manually define getter and setter methods. If val defines a field, only getters will be generated because its value is immutable. If a field with private is added and the field itself is private, its getter and setter methods are also private and can only be used in classes. It is defined as prviate[this], without getter and setter methods, and can only be used in the instance of the current class.

class Student {
  var name = "leo"
}
copy

Call getter and setter methods called name and name_respectively=

val leo = new Student
print(leo.name)
leo.name = "leo1"
copy

(3) Custom getter s and setter s If you just want to have simple getter and setter methods, you can choose the appropriate modifiers for the field according to the requirements according to the syntax rules provided by scala: var, val, private, private[this]. However, if you want to be able to control getter and setter by yourself, you can customize getter and setter methods. When customizing setter methods, you must pay attention to the syntax restrictions of scala, such as signature, = There cannot be spaces between parameters.

class Student {
  private var myName = "leo"
  def name = "your name is " + myName
  def name_=(newValue: String)  {
    print("you cannot edit your name!!!")
  }
}

val leo = new Student
print(leo.name)
leo.name = "leo1"
copy

(4) Only the getter method of the field is exposed If you don't want the field to have a setter method, you can define it as val, but you can't change the value of the field at this time. However, if you want to expose only one getter method and change the value of the field through some methods, you need to use both private and custom getter methods. At this time, since the field is private, both setters and getters are private and are not exposed to the outside world; You can implement the method of modifying the field value; You can override the getter method yourself.

class Student {
  private var myName = "leo"

  def updateName(newName: String) { 
    if(newName == "leo1") myName = newName 
    else print("not accept this new name!!!")
  }

  def name = "your name is " + myName
}
copy

(5) Use of private[this] If the field is decorated with private, it means that the field is private to the class. In the method of the class, you can directly access the private field s of other objects of the class. In this case, if you don't want the field to be accessed by other objects, you can use private[this], which means that the field private to the object can only be accessed in this object.

class Student {
  private var myAge = 0
  def age_=(newValue: Int) { 
    if (newValue > 0) myAge = newValue 
    else print("illegal age!") 
  }
  def age = myAge
  def older(s: Student) = {
    myAge > s.myAge
  }
}
copy

(6) Java style getter and setter methods The names of getter and setter methods in scala are different from those in java. They are field and field_= If you want Scala to automatically generate java style getter and setter methods, just add @ BeanProperty annotation to the field. At this time, four methods will be generated, name: String and name_=(newValue: String): Unit,getName(): String,setName(newValue: String): Unit.

import scala.reflect.BeanProperty
class Student {
  @BeanProperty var name: String = _
}
class Student(@BeanProperty var name: String)

val s = new Student
s.setName("leo")
s.getName()
copy

(7) Auxiliary constructor In Scala, you can define multiple auxiliary constructors for a class, which is similar to constructor overloading in java. Auxiliary constructors can call each other, and the main constructor must be called in the first line.

class Student {
  private var name = ""
  private var age = 0
  def this(name: String) {
    this()
    this.name = name
  }
  def this(name: String, age: Int) {
    this(name)
    this.age = age
  }
}
copy

(8) Main constructor In Scala, the main constructor is placed together with the class name, which is different from java. Moreover, the code in the class that is not defined in any method or code block is the code of the main constructor, which is not as clear as java.

class Student(val name: String, val age: Int) {
  println("your name is " + name + ", your age is " + age)
}
copy

In the main constructor, you can also use default parameters to give default values to parameters

class Student(val name: String = "leo", val age: Int = 30) {
  println("your name is " + name + ", your age is " + age)
}
copy

If the parameter passed in by the main constructor is not decorated, such as name: String, then if the method inside the class is used, it will be declared as private[this] name; Otherwise, without this field, it can only be used by the constructor code. (9) Inner class In Scala, you can also define internal classes in classes; But different from java, the internal class of the object of each external class is a different class.

import scala.collection.mutable.ArrayBuffer
class Class {
  class Student(val name: String) {}
  val students = new ArrayBuffer[Student]
  def getStudent(name: String) =  {
    new Student(name)
  }
}

val c1 = new Class
val s1 = c1.getStudent("leo")
c1.students += s1

val c2 = new Class
val s2 = c2.getStudent("leo")
c1.students += s2
copy

  1. The main constructor is directly followed by the class name, and the parameters in the main constructor will finally be compiled into fields or attributes
  2. When the main constructor is executed, all statements in the class will be executed
  3. If the parameter is declared without modifiers such as val or var, it is equivalent to private[this], which can only be used internally

2. Object object

(1)object Object is equivalent to a single instance of class. It usually contains some static field s or methods. When the object method is called for the first time, the constructor of the object will be executed, that is, the code inside the object that is not in the method; However, object cannot define a constructor that accepts parameters. Note that the constructor of object will only be executed once when it is called for the first time, and the constructor will not be executed again when it is called again in the future. Object is usually used as an implementation of singleton mode or as a static member of class, such as factory method.

object Person {
  private var eyeNum = 2
  println("this Person object!")
  def getEyeNum = eyeNum
}
copy

(2) Associated object If there is a class and an object with the same name as class, the object is called the associated object of class. Class is the associated class of object. The associated class and associated object must be stored in one scala file. The biggest feature of associated classes and associated objects is that they can access private field s.

object Person {
  private val eyeNum = 2
  def getEyeNum = eyeNum
}

class Person(val name: String, val age: Int) {
  def sayHello = println("Hi, " + name + ", I guess you are " + age + " years old!" + ", and usually you must have " + Person.eyeNum + " eyes.")
}
copy

(3) Let object inherit abstract classes In fact, the function of object is similar to that of class. In addition to not defining a constructor that accepts parameters, object can also inherit an abstract class and override the methods in the abstract class.

abstract class Hello(var message: String) {
  def sayHello(name: String): Unit
}

object HelloImpl extends Hello("hello") {
  override def sayHello(name: String) = {
    println(message + ", " + name)
  }
}
copy

(4) apply method A very important special method in object is the apply method. Usually, the apply method is implemented in the associated object and the function of constructing the object of the associated class is realized in it. When creating the object of the associated class, the apply method of the associated object is implicitly called in the way of Class() instead of new Class, which will make the object creation more concise. For example, the apply method of the associated object of the Array class realizes the function of receiving a variable number of parameters and creating an Array object.

val a = Array(1, 2, 3, 4, 5)
copy

For example, define your own companion classes and objects.

class Person(val name: String)
object Person {
  def apply(name: String) = new Person(name)
}
copy

(5) main method Just like in java, if you want to run a program, you must write a class containing the main method; In Scala, if you want to run an application, you must have a main method as the entry. The main method in scala is defined as def main(args: Array[String]) and must be defined in object.

object HelloWorld {
  def main(args: Array[String]) {
    println("Hello World!!!")
  }
}
copy

In addition to implementing the main method, you can also inherit app trail, and then directly use the code that needs to be run in the main method as the constructor code of the object; Moreover, args can accept the incoming parameters.

object HelloWorld extends App {
  if (args.length > 0) println("hello, " + args(0))
  else println("Hello World!!!")
}
copy

If you want to run the above code, you need to put it in Scala file, and then compile it with scalac, and then execute it in scala.

scalac HelloWorld.scala
scala -Dscala.time HelloWorld
copy

The working principle of APP train is: app train inherits from delayedInit train. When the scalac command is compiled, the constructor code of the object inheriting app train will be put into the delayedInit method of delayedInit train for execution. (6) Using object to realize enumeration function Scala does not directly provide Enumeration features like Enum in Java. If you want to implement Enumeration, you need to inherit the Enumeration class with object and call the Value method to initialize the Enumeration Value.

object Season extends Enumeration {
  val SPRING, SUMMER, AUTUMN, WINTER = Value
}
copy

You can also pass in the id and name of the enumeration Value through Value, which can be obtained through id and toString; You can also find enumeration values by id and name.

object Season extends Enumeration {
  val SPRING = Value(0, "spring")
  val SUMMER = Value(1, "summer")
  val AUTUMN = Value(2, "autumn")
  val WINTER = Value(3, "winter")
}
Season(0)
Season.withName("spring")
copy

Use enumeration object Values can traverse enumerated values

for (ele <- Season.values) println(ele)
copy

Posted by Randomizer on Sun, 08 May 2022 10:02:09 +0300