Data Class
A Data class can be used to create a Data class to store Data. These classes will automatically provide methods like setter, getter, Copy,toString(),hashCode(),componentN()
data class User(val name: String, val id: Int) // 1 fun main() { val user = User("Alex", 1) println(user) // 2 val secondUser = User("Alex", 1) val thirdUser = User("Max", 2) println("user == secondUser: ${user == secondUser}") // 3 println("user == thirdUser: ${user == thirdUser}") println(user.hashCode()) println(secondUser.hashCode()) // 4 println(thirdUser.hashCode()) // copy() function println(user.copy()) // 5 println(user.copy("Max")) // 6 println(user.copy(id = 2)) // 7 println("name = ${user.component1()}") // 8 println("id = ${user.component2()}") } /* User(name=Alex, id=1) user == secondUser: true user == thirdUser: false 63347075 63347075 2390846 User(name=Alex, id=1) User(name=Max, id=1) User(name=Alex, id=2) name = Alex id = 1 */Copy the code
- 1 Define a data class
- 2
println
The output of dataclasstoString()
Method return value - 3 automatic coding
equals()
The method takes into account that if all attributes of both instances are equal, then both instances will be equal - 4 Equal dataclass Hashcode will also return the same Hashcode in the case of equals
- 5 automatically coded
copy()
Method will make it easy to create a copy - When you select copy, you can easily modify internal properties. You can pass in the corresponding values in the constructor order
- You can also modify specific parameters by naming them
- 8 automatically coded
componentN()
Method that lets you read the values of each field in the order in which the properties are defined
Enum class enumeration
Enumeration classes are equivalent to ground enumeration in Java
enum class State {
IDLE, RUNNING, FINISHED // 1
}
fun main() {
val state = State.RUNNING // 2
val message = when (state) { // 3
State.IDLE -> "It's idle"
State.RUNNING -> "It's running"
State.FINISHED -> "It's finished"
}
println(message)
}
Copy the code
- Define an enumeration class with three instances, each of which is unique and fixed, and the number of enumerations is fixed and immutable.
- 2 can access an enumerated instance by its class name.
- We explicitly use the else field when we use when as an expression. But when an when expression encounters an enumeration, as long as you list all the enumeration variables, you don’t need an else field
Enumerating classes, or you can define method fields and so on inside a class, as Java does. In this case you need to explicitly use semicolons to separate enumerated instances from other elements of the class.
enum class Color(val rgb: Int) { // 1 RED(0xFF0000), // 2 GREEN(0x00FF00), BLUE(0x0000FF), YELLOW(0xFFFF00); fun containsRed() = (this.rgb and 0xFF0000 ! = 0) // 3 } fun main() { val red = Color.RED println(red) // 4 println(red.containsRed()) // 5 println(Color.BLUE.containsRed()) // 6 }Copy the code
- Define an enumerated class with an attribute and a method
- Each instance must pass an explicitly different attribute value
- Methods need to be separated by semicolons and strength definitions
- 4 Generated by default
toString
Method, which defaults to the name of the enumeration, as printed hereRED
. - 5 the current instance will be called here
containsRed
methods - You can also use the class name to read the instance and then call its methods
Sealed Classes
Sealed Class The sealed class is used to limit inheritance. If you define a sealed class, its subclasses must be defined in the same file. Subclasses are not allowed to be defined in other files,
sealed class Mammal(val name: String) // 1
class Cat(val catName: String) : Mammal(catName) // 2
class Human(val humanName: String, val job: String) : Mammal(humanName)
fun greetMammal(mammal: Mammal): String {
when (mammal) { // 3
is Human -> return "Hello ${mammal.name}; You're working as a ${mammal.job}" // 4
is Cat -> return "Hello ${mammal.name}" //5
is Mammal -> return "Hello ${mammal.name}"
} //6
}
fun main() {
println(greetMammal(Cat("Snowy")))
println(greetMammal(Human("John", "IT")))
//println(greetMammal(Mammal("John"))) // 7
}
/*
Hello Snowy
Hello John; You're working as a IT
*/
Copy the code
- Define a sealed class
- Define a subclass. this subclass must be defined in the same file
- Note: In this method, there is no need to define the else field in the when expression because it is exhausting all the possibilities.7Cannot access: it is private in ‘keepers’
Sealed types cannot be instantiated`
- There will be a quick forced conversion to convert the Mammal to Human
- 5 a quick force conversion will take place to convert the Mammal to Cat
- There is no need for the else field because all subclasses explicitly override it
- This sentence will result in an error
Object Keyword
Classes and objects are much the same in Kotlin and other object-oriented languages: a class is a blueprint and an object is an instance of a class. Typically, you define a class and then create instances of multiple classes.
import java.util.Random
class LuckDispatcher { //1
fun getNumber() { //2
var objRandom = Random()
println(objRandom.nextInt(90))
}
}
fun main() {
val d1 = LuckDispatcher() //3
val d2 = LuckDispatcher()
d1.getNumber() //4
d2.getNumber()
}
Copy the code
- 1 Define a blueprint
- 2 Define a method
- 3 Create a blueprint instance
- 4 Invoke the instance method
In Kotlin you have a definition object Keyword. This is often used to define a unique implementation. In Java, you can think of this as a singleton pattern: when two threads want to create instances of the class, only one instance is guaranteed.
In Kotlin, you declare only one object: no class definition, no constructor, and only a lazy instance. According to the lazy? Because it will only be created when it is accessed, on the other hand: it may not even be created
object
Expression
This is a basic use of object Expression: a simple object or structure of data. You don’t need to define a class declaration here: you just create an object and declare its members, and use it in a method. Such objects exist in Java as instances of anonymous inner classes.
fun rentPrice(standardDays: Int, festivityDays: Int, specialDays: Int): Unit { //1
val dayRates = object { //2
var standard: Int = 30 * standardDays
var festivity: Int = 50 * festivityDays
var special: Int = 100 * specialDays
}
val total = dayRates.standard + dayRates.festivity + dayRates.special //3
print("Total price: $$total") //4
}
fun main() {
rentPrice(10, 2, 1) //5
}
Copy the code
- 1 Create a method with three parameters
- Create an object and calculate and save three results
- Access the value in the structure of this object
- 4 Printing Results
- 5 Run this method. The object will be created only when the method is run
object
Declaration
You can also declare object, which is not an expression and cannot be used in assignment statements. You are better off accessing its members directly by the class name
object DoAuth { //1
fun takeParams(username: String, password: String) { //2
println("input Auth parameters = $username:$password")
}
}
fun main(){
DoAuth.takeParams("foo", "qwerty") //3
}
Copy the code
- 1 Create an object declaration
- 2 Define a method in object
- 3 execute, where object is actually created.
Companion Objects Internal Objects
Another use of object declared inside a class is Companion Objects. Syntactically, this is more like static methods in Java. If you want to use the Companion Object in Kotlin. Use the package-level class method definition.
class BigBen { //1
companion object Bonger { //2
fun getBongs(nTimes: Int) { //3
for (i in 1 .. nTimes) {
print("BONG ")
}
}
}
}
fun main() {
BigBen.getBongs(12) //4
}
Copy the code
- 1 Define a class
- 2 Define a Companion, and the display defines the name
- 3 defines a Companion Object method,
- 4 Access the Companion Object’s methods directly through its class name