First, preface
Learn Scala's methods and then learn about object in Scala
Second, Object
There are two meanings of object in Scala, in Java, which represents an instance of a class, and in Scala it's a keyword, and this article will first look at object as an instance of a class, showing how to convert objects from one type to another. We'll show you how to create a singleton, and there's a package object in Scala, which is often defined as follows
Type Throwable = Java.lang.Throwabletype Exception = Java.lang.Exceptiontype Error = java.lang.Errortype Seq[+a] = scala.c Ollection. Seq[a]val Seq = Scala.collection.Seq
Using the type definition can make the code more concise, use the associated object to create a static method, and the companion object can make it unnecessary to use the new keyword when creating the class object, as shown below
Val siblings = List (Person ("Kim"), Person ("Julia"), Person ("Kenny")
2.1 Object Conversions
1. Description of the problem
You need to convert an instance of a class from one type to another, such as dynamically created objects
2. Solution
Use the Asinstanceof method for type conversion, as the object returned by the lookup method below will be converted to a Recognizer object
Val recognizer = cm.lookup ("recognizer"). Asinstanceof[recognizer]
The above code is in Java as follows
Recognizer recognizer = (recognizer) cm.lookup ("recognizer");
The Asinstanceof method is defined in the any class, so the method can be used in any class
3. Discussion
In dynamic programming, it is often necessary to convert from one class to another, such as using a Pplicationcontext file in the Spring Frameworkto initialize the bean
Open/read The application context fileval CTX = new Classpathxmlapplicationcontext ("Applicationcontext.xml")// Instantiate our dog and Cat objects from the application Contextval dog = Ctx.getbean ("dog"). Asinstanceof[animal]val cat = Ctx.getbean ("Cat"). Asinstanceof[animal]
You can also use the Asinstanceof method when converting to a digital type
You can also use the Asinstanceof method when you need to interact with Java
Val objects = Array ("A", 1) Val arrayofobject = Objects.asinstanceof[array[object]]ajavaclass.sendobjects ( Arrayofobject)
Like Java, type conversions can throw classcastexception exceptions
You can use Try/catch to resolve this issue
2.2 Methods corresponding to the Java. class
1. Description of the problem
When an API requires you to pass a class object, in Java, you can use the. class, but in Scala it won't work.
2. Solution
Use Scala's Classof method, as shown below
Val info = new Dataline.info (Classof[targetdataline], NULL)
In Java, use the following
info = new Dataline.info (targetdataline.class, NULL);
The Classof method is defined in the Predef object, so it can be used directly without an import
3. Discussion
This method lets you begin to learn reflection, as the following example can access the method of the String class
2.3 Determining the class of an object
1. Description of the problem
In Scala, you don't need to display the type of claim, and you occasionally want to print the class or type of an object to understand how Scala works
2. Solution
You can use the GetClass method of the object to determine the type of Scala that is automatically assigned to you, such as when you need to understand the workflow of mutable parameters, you can call the GetClass method, and know that different cases and types are not the same
def printall (numbers:int*) { println ("class:" + Numbers.getclass)}
When calling the Printall method with multiple parameters and calling the Printall method without using arguments, the result is different
This method works well when working with Scala's XML library, knowing the classes that are handled under different circumstances, including a subclass under the,<p> tag below.
When the <br/> tag is added to the <p> tab, the results are as follows
3. Discussion
If you do not know the type of the object in the IDE, you can use the GetClass method to get the object type
2.4 Starting an app with an object
1. Description of the problem
You want to use the main method to start an app, or to provide a portal for the script
2. Solution
There are two ways to launch an app, one to let the class inherit the app, and the other to define an object and define the Main method
For the first method, the general practice is as follows
Object Hello extends App { println ("Hello, World")}
The statement inside the object executes automatically, and the second method defines the Main method
Object Hello2 { def main (args:array[string]) { println ("Hello, World") }}
3. Discussion
In both of these methods, the application is started by using object
2.5 Creating a singleton with object
1. Description of the problem
You want to create a singleton object
2. Solution
Use the object keyword to create a singleton object
Object Cashregister { def open {println ("opened")} def close {println ("closed")}}
Since cashregister is defined as an object, there is only one instance, and the method being called is equivalent to a static method in Java, called as follows
Object Main extends App { cashregister.open cashregister.close}
This method works equally well when you create a tool method
Import Java.util.Calendarimport java.text.SimpleDateFormatobject dateutils { //as "Thursday, November" def getcurrentdate:string = GetCurrentDateTime ("eeee, MMMM D") //as "6:20 p.m." def getcurrenttime:string = GetCurrentDateTime ("k:m AA") //A common function used by other date/time functions p Rivate def getcurrentdatetime (datetimeformat:string): String = { val dateformat = new SimpleDateFormat ( DateTimeFormat) val cal = calendar.getinstance () Dateformat.format (Cal.gettime ()) }}
Because the method is defined in object, you can call these methods directly using Dateutils, just as you call a static method in Java
DateUtils.getCurrentDateDateUtils.getCurrentTime
When using actors, singleton objects can produce reusable messages, and if you have an actor that can accept and send messages, you can create a singleton using the following method
Case Object Startmessagecase Object Stopmessage
These objects will be treated as messages and can be passed to the actor
Inputvalve! Stopmessageoutputvalve! Stopmessage
3. Discussion
When using a companion object, a class can have both a non-static method and a static method
2.6 Creating a static member with a companion object
1. Description of the problem
You want to create an instance method and a class method for a class, but there is no static keyword in Scala
2. Solution
Define a non-static member in class, define a static member in object, have the same name as the class and be in the same file, which is called the companion object
Use this method to let you create static members (fields and methods)
Pizza Classclass Pizza (var crusttype:string) { override def toString = "Crust type is" + crusttype}//companion Objectobject Pizza { val crust_type_thin = "THIN" val crust_type_thick = "THICK" def getfoo = "Foo"}
The Pizza class and the Pizza object are in the same file (Pizza.scala), and the members in the Pizza object are equivalent to the static members in the Java class
println (Pizza.crust_type_thin) println (Pizza.getfoo)
You can also create pizza objects in the usual way
var p = new Pizza (Pizza.crust_type_thick) println (p)
3. Discussion
Class and object have the same name and are non-static members defined in class in the same file, and static members are defined in object
Class and its associated objects can access each other's private members, such as the double method of the following object to access the private variables in class secret
Class Foo { private val secret = 2}object Foo { //access the Private Class field ' secret ' def double (foo:foo ) = Foo.secret * 2}object Driver extends App { val f = new Foo println (foo.double (f))//Prints 4}
Static private variables in the associated object can be accessed by non-static methods in the following class class
Class Foo { //access the Private Object field ' obj ' def printobj {println (S "I can see ${foo.obj}")}}object Foo { private val obj = "Foo ' s object"}object Driver extends App { val f = new Foo F.printobj}
2.7 Putting common code in a package object
1. Description of the problem
You want to make methods, fields, and other code at the package level without requiring class or object
2. Solution
Place the code under the package object, such as placing your code in the Package.scala file, for example, if you want the code to be available for all classes under the Com.hust.grid.leesf.model package, create a com/hust/grid/leesf/ The Package.scala file in the Model directory, in Package.scala, removes the model from the package declaration and creates the package as its name, roughly as follows
Package Com.hust.grid.leesfpackage Object Model {
The other code is placed in the model, as shown below
Package Com.hust.grid.leesfpackage Object Model { //field val magic_num =/ /method def Echo (A:any) { println (A)} //Enumeration object margin extends enumeration { type Margin = Value val TOP, BOTTOM, left , right = Value } //Type definition type mutablemap[k, v] = scala.collection.mutable.map[k, V] Val Mut Ablemap = Scala.collection.mutable.Map}
At this time, under the Com.hust.grid.leesf.model package class, object, interface, etc. can freely access the above defined fields, methods, etc.
Package Com.hust.grid.leesf.modelobject Maindriver extends App { //access to our method, constant, and enumeration Echo ("Hello, World") echo ( magic_num) Echo (margin.left) //With our Mutablemap type ( SCALA.COLLECTION.MUTABLE.MAP) val mm = Mutablemap ("name", "Al") mm + = ("password", "123") for (K, V) <-mm) printf ("Key:%s, Value:%s\n", K, V)}
3. Discussion
The most confusing thing is where to put the package object, its name and the name of the object
If you want your code to be visible in the Com.hust.grid.leesf.model package, put Package.scala in the Com/hust/grid/leesf/model directory, In Package.scala, the package name should be the following
Package COM.HUST.GRID.LEESF
Then use model as the object name
Package Object Model {
The final approximation is as follows
Package Com.hust.grid.leesfpackage Object Model {
The package can hold enumeration types, constants, and implicit conversions
2.8 Creating an object instance without using the New keyword
1. Description of the problem
When you create an object without using the New keyword, the Scala code appears relatively concise, as shown below
Val A = Array (person ("John"), Person ("Paul"))
2. Solution
There are two ways of
· Create a companion object for the class, and then define the Apply method with the same signature as the constructor method
· To define a class as a case class
The associated object is defined for the person object, then the Apply method is defined and the parameter is accepted
Class Person { var name:string = _}object Person { def apply (name:string): person = { var p = new person
p.name = name p }}
Now you can create a person object without using the New keyword.
Val Dawn = Person ("Dawn") val a = Array (person ("Dan"), Person ("Elijah"))
The Scala compiler has special handling of apply in the associated object, allowing you to create objects without using the New keyword
Define the class as a case class and accept the corresponding parameter
Case class Person (Var name:string)
You can now create objects in the following ways
Val p = person ("Fred flinstone")
Scala creates an apply method for the associated object of the case class
3. Discussion
The compiler will take special care of the associated object's apply, which is Scala's syntax sugar
Val p = person ("Fred flinstone")
The code above will be converted to the following code
Val p = person.apply ("Fred flinstone")
The Apply method is the factory method, Scala's syntax sugar lets you create objects without the New keyword
You can create multiple apply methods in the associated object, which is equivalent to multiple constructors
Class Person { var name = ' "" var = 0}object person { //a One-arg constructor def apply (name:string): person = { var p = new person p.name = name p } //A Two-arg constructor def apply (name:string, Age:int): person = { var p = new person p.name = name P.age = Age P }}
You can create objects using the following methods
Val fred = Person ("Fred") Val john = person ("John", 42)
To create multiple constructors for the case class, you need to know the logic behind the case class
When compiling the case class using the Scala compiler, you will see that it generates two files, Person$.class and Person.class files, when using JAVAP to decompile the Person$.class file, its output is as follows
It contains an apply method that returns the Person object
Public person apply (java.lang.String);
String corresponds to the name in the case class
Case class Person (Var name:string)
Use the JAVAP command to see the getter and setter functions generated for name in Person.class
In the following code, there is the case class and the Apply method
Want accessor and mutator methods for the name and age Fieldscase class person (Var name:string, var age:int)//Defin e-Auxiliary constructorsobject person { def apply () = new Person ("<no name>", 0) def apply (name:string) = new Person (name, 0)}
Because both name and age are Var, getter and setter are generated, and two apply functions are defined in object, so you can generate a person object in three ways:
Object Test extends App { val a = person () val b = Person ("Al") val c = Person ("William Shatner", Prin) TLN (a) println (b) println (c) //Test the mutator methods a.name = "Leonard Nimoy" a.age = 82 println (A)}
The results are as follows
Person (<no name>,0) person (al,0) person (William shatner,82) person (Leonard nimoy,82)
2.9 Using apply to implement factory methods
1. Description of the problem
In order for a subclass to declare what type of object it should create and only be able to create objects in one place, you want to implement the Factory method
2. Solution
You can use the Apply method of the associated object to implement the Factory method, and you can place the factory implementation algorithm in the Apply method
Suppose you want to create a animal factory and return cat and dog, implement the Apply method in the companion object of the animal class, and you can create different objects using the following method
Val cat = Animal ("cat")//Creates a catval dog = Animal ("dog")//Creates a dog
First, you need to create a animal trait
Trait Animal { def speak}
Then create the associated object in the same file, create a class that implements animal, an appropriate apply method
Object Animal { Private class Dog extends Animal { override def speak {println ("Woof")} } private class Cat extends Animal { override def speak {println ("Meow")} } //The factory method def apply (s:string): Animal = { if (s = = "dog") New dog else new Cat }}
You can then create different objects using the following statement
Val cat = Animal ("cat")//Creates a catval dog = Animal ("dog")//Creates a dog
3. Discussion
If you do not use the Apply method to implement the factory method, you can also use the following Getanimal method to implement the above functions
An alternative factory method (with one or the other) def Getanimal (s:string): Animal = { if (s = = "Dog") return new Dog else return new Cat}
You can then use the following methods to create different objects
Val cat = Animal.getanimal ("cat")//Returns a catval dog = Animal.getanimal ("dog")//Returns a dog
Both of these methods are feasible
Iii. Summary
This article has learned about object in Scala and its corresponding usage, and it is widely used in Scala's practical programming.
Scala object (apply) dycopy