I am also a beginner in Kotlin, if there is any mistake, please help to point out, continue to update

Android: Kotlin Tutorial – Classes and Objects – Basic Syntax (4)

Android: Kotlin Learning Guide – Basic Syntax (1)

Android: Kotlin Tutorial – Basic Types – Basic Syntax (2)

Android: Kotlin – Package – Control Flow – Return and jump – Basic syntax (3)

This article to share more content, it is recommended to pay attention to the collection, and then view, so as not to get lost

Classes and objects

  • Class and inheritance
  • Properties and fields
  • interface
  • Visibility modifiers
  • extension
  • The data object
  • The generic
  • Nested classes
  • Enumeration class
  • Object expressions and declarations
  • Delegate pattern
  • Delegate properties
Class and inheritance
class

In Kotlin, classes are declared as class:

class Invoice {}Copy the code

The declaration of a class contains the class name, the class header (specifying type parameters, main constructors, and so on), and the class body, wrapped in large brackets. Class headers and class bodies are optional; You can omit the braces if there is no class body.

The constructor

Kotlin’s constructors are somewhat different from Java’s in that Kotlin classes can have a primary constructor and multiple secondary constructors. The main constructor is part of the class header: it follows the class name (which can have optional type arguments).

class Person constructor(firstName: String) { }
Copy the code

If the main constructor does not have an annotation or visibility statement, the constructor keyword can be omitted:

class Person(firstName: String){ }
Copy the code

The main constructor cannot contain arbitrary code. The initialization code can be placed in an initialization block prefixed with init

class Customer(name: String) { 
	init {
		logger,info("Customer initialized with value ${name}")}}Copy the code

Note that the arguments to the main constructor can be used in the initializer block or in the class attribute initializer declaration:

class Customer(name: String) { 
	val customerKry = name.toUpperCase() 
}
Copy the code

Declaring attributes and initializing them in the main constructor has a simpler syntax in Kotlin

class Person(val firstName: String, val lastName: String, var age : Int) {}Copy the code

Properties in the main constructor can be mutable (var) or read-only (val). If the constructor has an annotation or visibility declaration, the constructor keyword is required

Secondary constructor

Overloaded java-like classes can also have secondary constructors that need to be prefixed by constructor:

class Person { 
	constructor(parent: Person) { 
		parent.children.add(this)}}Copy the code

If the class has a primary constructor, each secondary constructor must, either directly or indirectly, proxy the primary constructor through another secondary constructor. Proiding another constructor in the same class using the this keyword:

class Person(val name: String) { 
	constructor (name: String, paret: Person) : this(name) { 
		parent.children.add(this)}}Copy the code

If a non-abstract class does not declare a constructor (primary constructor or secondary constructor), it produces a constructor with no arguments. The constructor’s visibility is public. If you don’t want your class to have a public constructor, you should declare an empty main constructor with non-default visibility:

class DontCreateMe private constructor () {}Copy the code

Note: In the JVM virtual machine, if all arguments to the main constructor have default values, the compiler generates an additional constructor with no arguments, which uses the default values directly. This makes it easier for Kotlin to use libraries like Jackson or JPA that use no-argument constructors to create class instances.

Create an instance of the class
val invoice = Invoice() 
val customer = Customer("Joe Smith")
Copy the code

Note that Kotlin does not have the new keyword. Inner classes use the inner keyword.

Members of the class

Classes can contain:

  • Constructor and initialization code block
  • function
  • attribute
  • The inner class
  • Object statement
inheritance

All classes in Kotlin have a common parent class, Any. Java is Obejct, which is the default parent of a class that has no parent declaration: Any is not java.lang.object; It actually has no members other than equals(), hashCode(), and toString(). To declare an explicit parent, add a colon after the class header

open class Base(p: Int) 
class Derived(p: Int) : Base(p)
Copy the code

Ordinary classes need the open keyword if they want to be inherited. The open annotation is the opposite of final in Java: it allows other classes to inherit the class. By default, all classes in Kotlin are final

Copying method
open class Base { 
	open fun v(a) {} 
	fun nv(a){}}class Derived() : Base() { 
	override fun v(a){}}Copy the code

The override annotation is required for Derived. V (). If not, the compiler prompts. Without the open annotation, like base.nv (), it is illegal to declare the same function in a subclass, either with override or without override. In final classes (that is, classes without the open annotation), members of type open are not allowed. The normal method, marked open, can be overridden

Copy attributes

Override properties are similar to override methods in that properties declared on a parent class must be redeclared on a subclass, and they must have compatible types. Each declared property can be overridden by a property with an initializer or a property with a getter

Autotype rules

In Kotlin, implementation inheritance generally follows the following rule: if a class inherits multiple implementations of the same member from its immediate parent, it must clone that member and provide its own implementation (or perhaps just use the inherited implementation directly). To indicate using methods provided in the parent class we use super:

open class A { 
	open fun f (a) { 
		print("A")}fun a(a) { 
		print("a")}}interface B { 
	fun f(a) { 
		print("B")}// Interface member variables are open by default
fun b(a) { 
	print("b")}}class C() : A() , B { 
// The compiler will require a copy of f()
	override fun f(a) { 
		super<A>.f() / / call A.f ()
		super<B>.f() / / call b. ()}}Copy the code

Methods can be inherited from both A and B, and C has no problem inheriting the implementation of either A () or B (), since there is only one implementation for both. But f() has two implementations, so we have to duplicate f() in C and provide our own implementations to disambiguate it. That’s it for now, and I’ll continue next time.

I am also a beginner in Kotlin, if there is any mistake, please help to point out, continue to update