Android development knowledge learning - Kotlin basics

function declaration

To declare a function, use the fun keyword, just like you use the class keyword to declare a class.
The "parameter type" of the "function parameter" is on the right side
of the "parameter name". The "return value" of the function is used on the right side of the "function parameter": separated, can be omitted if there is no return value

  • Declare a function without a return value:
 fun main(){
    
    
        println("123")
    }
  • Declare parameters with return values:
 fun sum(x:Int,y:Int):Int{
    
    
        println("123")
    }

variable declaration

  • You need to use keywords to declare variables. var declares readable and writable variables, and val declares read-only variables.

  • "Type" is on the right side of "Variable name", separated by:. At the same time, if "type inference" is satisfied, the type can be omitted.

  • Create an object and call the constructor directly without the new keyword.

  • Declare readable and writable variables:

var x: Int= 1
  • Declare read-only variables:
val username:String = "username"
  • declare object
val user:User = User()

type inference

If the type of the right-hand side of the expression can be inferred based on the variable declaration, the type can be omitted:

var age = 18
val name = "Hello"
val user = User()

Inherited class/implemented interface

Both inherited classes and implemented interfaces use: . If there is no constructor in the class, you need to add () after the parent class name:

class MainActivity : AppCompatActivity(),View.OnClickListener{
    
    
	}

This is how it works in Java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    
    
}

Null safety design

Types in Kotlin are divided into "nullable types" and "non-nullable types":

  • non-nullable type
val username: EditText
  • nullable type
val username: EditText?

caller

  • !!Force caller
  • ?.safe caller

lateinit keyword

The lateinit keyword indicates that a variable can be initialized after its initialization expression is executed.

  • lateinitOnly varreadable and writable variables can be modified, because val defines the variable as immutable and must be initialized when declared.
  • lateinitThe type of the variable declared by the keyword must be a "non-nullable type"
  • lateinitThe declared variable cannot have an "initial value"
  • lateinitThe declared variable cannot be a "basic data type".
    Attributes initialized in the constructor do not require lateinitthe keyword

platform type

The type with an exclamation mark after the type is a "platform type". In Java, annotations can be used to reduce the occurrence of such platform types.

  • @NullableRepresents a nullable type
  • @NotNull @NonNul lIndicates a non-nullable type

Type judgment

  • isDetermine whether it belongs to a certain type
    Insert image description here

  • !isJudgment does not belong to a certain type
    Insert image description here

  • asType coercion will throw a type coercion failure exception when it fails.
    Insert image description here

  • as?Type coercion, but does not throw an exception but returns when it failsnull

Get Class object

  • Using class name::class to get the Kotlin type is KClass
MainActivity::class
  • Use class name::class.java to get the Java type
startActivity(Intent(this,test::class.java))

setter/getter

When a property is declared in Kotlin (without privatemodification), a private property and a pair of public setter/getterfunctions are automatically generated. Use instead of internal private properties
when writing (to prevent recursive stack overflow )setter/getterfield

class User {
    
    
var username : String?= null
var password : String?= null
    
    set(value) {
    
    
        field = value
    }
    
    get() {
    
    
        return field
    }
    
    //构造器
    constructor(){
    
    
        
    }

    constructor(username : String?,password : String?){
    
    
        this.username = username
        this.password = password
    }
}

Why can EditText.getText() be simplified, but EditText.setText() cannot be
simplified in the same way as TextView.setText()?
Because the type obtained by EditText.getText() is Editable, and correspondingly if EditText.setText() passes It can be simplified if the entered parameters are also Editable.

val newEditable= Editable.Factory.getInstance().newEditable("Kotlin") et_username.text = newEditable 

Constructor

Declare a constructor using the constructor keyword

    //构造器
    constructor(){
    
    
        
    }

    constructor(username : String?,password : String?){
    
    
        this.username = username
        this.password = password
    }

If we actively call the parent class constructor in the constructor, we cannot add parentheses after the class when inheriting the class.

constructor(context: Context) : this(context, null)
// 主动调用用了父类的构造器
constructor(context: Context, attr: AttributeSet?) :
super(context, attr)

@JvmField generated properties

Through the @JvmField annotation, the compiler can only generate a public member property and not generate the corresponding setter/getter function.

   @JvmField
var username : String?= null
 User user = new User();
 String username = user.username;

Any and Unit

  • The top-level parent class of Any
    Kotlin is Any, which corresponds to Object in Java, but it lacks wait()/notify() and other functions than Object.
class User : Any {
    
    }
  • Unit Unit
    in Kotlin corresponds to void in Java
 fun get():Unit{
    
    }

array

Use arrayof() to create an array, and use the corresponding intArrayOf() for basic data types, etc.

val list:Array<String> = arrayOf("1", "2", "3", "4")
val Intlist:IntArray = intArrayOf(1, 2, 3, 4)

Static functions and properties

  • Top-level function
    A top-level function that does not depend on any specific object or class. Top-level functions can be used directly anywhere without creating an instance of the class

Class name. Call method

class MyClass {
    
    
    fun greet(name: String): String {
    
    
        return "Hello, $name"
    }
}

Then you can create an instance of the class and call its methods like this:

val myClass = MyClass()  // Create an instance of MyClass
val greeting = myClass.greet("John")  // Call the greet() method on the instance
println(greeting)  // Prints: Hello, John
  • object
    Insert image description here
    Insert image description here
    Insert image description here
  • Among the companion objects
    Insert image description here
    Insert image description here
    , the "top-level function" directly defines functions and properties in the file, which will be directly generated statically and can be accessed through "file name Kt" in Java. At the same time, @file:JvmNamethe "class name" can be modified through annotations. It should be noted that this kind of top-level function should not be declared in modulethe top-level package, but must be in at least one package. For example com. Otherwise it will not be convenient to use. objectand companion objectboth generate singleton objects, and then access functions and properties through the singleton object.

@JvmStatic

Through this annotation, the internal functions and properties of objectand companion objectare truly generated as static.
The @JvmStatic annotation is usually used to mark static methods or variables that need to be accessed directly in the JVM. When the Kotlin code is compiled into JVM bytecode, the annotation processor inserts these static methods and variables into the generated Java class. The
Insert image description here
greet() method is marked with the @JvmStatic annotation. When this Kotlin class is compiled into a Java class, the greet() method is inserted into the generated Java class and can be accessed directly through the class name without creating an instance of the Kotlin class.

In Java, you can call the currentApplication() method like this:
Insert image description here

Singleton pattern/anonymous inner class

objectImplemented through keywords

// 单例
object Singleton {
    
    
}
// 匿名内部类
object : Callback {
    
    
}

string

String template

Use ${}the form as a string template

val number = 100000000
val text = "支付宝收款${
      
      number}元。"
// 如果只是单一的变量,可以省略掉 {}
val text2 = "支付宝收款$number元。

multiline string

val s = """
我是第一行
我是第二行
我是第三行
""".trimIndent()

interval

200…299 represents the interval from 200 -> 299 (including 299)

300…399 represents the interval from 300 -> 399 (including 399)

when keyword

The advanced version of Java switchcan support expressions in branch conditions.
Insert image description here

checked exception

Kotlin does not need to use try-catchforced exception catching

Declare interface/abstract class/enumeration/annotation

// 声明抽象类
abstract class

// 声明接口
interface

// 声明注解
annotation class

// 声明枚举
enmu class

compile time constants

Adding the keyword to a static variable constbecomes a compile-time constant
. The const keyword can be used to declare a compile-time constant. This constant must be assigned a value when declared, and must be a literal value, not a function call or expression. Additionally, const constants must be read-only and cannot be modified at runtime
Insert image description here

Label

  • Obtain the target class reference through " 类名.thisfor example " in JavaOuter.this
    Insert image description here

  • Get the target class reference through " this@类名for example " in Kotlinthis@Outer
    Insert image description here

Traverse

Remember to let the IDE help generate the for loop

for(item in items)

Insert image description here

inner class

In Kotlin, inner classes are static inner classes by default and are declared as nested inner classes
using the keywordinner
Insert image description here

visibility modifier

The default visibility modifier is public
the new visibility modifier, which internalindicates the visibility of the current module.

Comment

You can use [] anywhere in the comment to refer to the target, instead of @param @linketc. in Java.

non-null assertion

Type conversion from a nullable type to a non-nullable type can be achieved by adding !! after the variable.

open/final

Classes and functions in Kotlin are finaldecorated ( abstractand overrideexceptions) by default

After-school questions

  1. Will the kotlin compiler create a constructor by default?

In Kotlin, constructors, like other parts of a class, need to be explicitly declared. If you do not declare a constructor, the Kotlin compiler will generate a default no-argument constructor for you . This default constructor does not call any code, i.e. it is an empty function

  1. var username : String?= “123”

Declare a variable variable named username, its type is String? (nullable string), and initialized to "123". If you need to change
the value of username, you can directly assign it a new string or null.

  1. public var age : Int = 0

In Kotlin, public var age : Int = 0and @JvmField var age : Int = 0
can both be used to declare a public, mutable, integer variable initialized to 0 in Kotlin. However, the two are not entirely equivalent. public var age : Int = 0Variables are declared directly in Kotlin, and their default visibility is publicthat they can be accessed by any other code. Instead
@JvmField var age : Int = 0use annotations @JvmField, which generate a Java
field visible in . @JvmFieldThe purpose is to allow variables in Kotlin to be represented as fields in Java code instead of being accessed through
getterthe and settermethods. The main difference between the two is that if you need to access Kotlin variables directly in Java (instead of through
getters and setters), then you need to use @JvmField. If you are only using this variable inside Kotlin or elsewhere that supports Kotlin
, then you can use it directly public var age : Int = 0.
Generally speaking, the two are not substitutes for each other, but you choose which one to use based on the specific usage scenario.

  • Example:
    Suppose you have the following Kotlin class definition:
class Person {
    
    
    var name: String = "John"
    @JvmField var age: Int = 0
}

If you use @JvmField, you can access and modify the age variable directly in Java as follows:

Person person = new Person();
person.age = 25; // 可以直接修改 age 变量
int age = person.age; // 通过字段获取 age 值

However, if you remove @JvmField and use public var age: Int = 0, you can still access and modify the age variable directly in Kotlin, but in Java you need to access it through getter and setter methods:

Person person = new Person();
person.setAge(25); // 通过 setter 方法修改 age 值
int age = person.getAge(); // 通过 getter 方法获取 age 值

Therefore, the main purpose of using @JvmField is to directly access Kotlin properties in Java without using getter and setter methods . If you only use this property in Kotlin, then using public var age: Int = 0 is enough. However, if you need to interoperate with Java code and want to access Kotlin properties directly in Java, then using @JvmField is a more appropriate choice.

  1. this in Kotlin.
    In Kotlin, the this keyword has a special meaning. It is used to refer to the current object instance.
    In Kotlin, the this keyword has several uses:
  • Directly refer to the instance of the current object: In a class method, you can use the this keyword to refer to the currently executing object instance . For example:
class MyClass {
    
    
    var name: String? = null

    fun printName() {
    
    
        println(this.name)
    }
}

In this example, the this keyword refers to the object instance being executed, and the name attribute of the instance is printed.

  • Reference the properties or methods of the current object : When you need to access its properties or methods through an object, you can use the this keyword. For example:
class MyClass {
    
    
    var name: String? = null

    fun printName() {
    
    
        println(this.name)
    }
}

In this example, the this keyword refers to the object instance being executed, and the name attribute of the instance is printed.

  • Reference external variables in anonymous functions or Lambda expressions : In anonymous functions or Lambda expressions, you can use the this keyword to refer to external variables. For example:
fun outerFunction() {
    
    
    val x = 10
    val action = object : Action<Int> {
    
    
        override fun run(input: Int) {
    
    
            println("Value of x from outer function: $x") // Here, 'this' refers to the outer function's 'x' variable.
        }
    }
    action.run(5)
}

In this example, the this keyword refers to the variable x of the external function.

  1. [Essay question] Use Kotlin to obtain code referenced by external classes

val outer = /* external class reference*/

If you want to get a reference to an outer class in Kotlin, you need to first define that outer class as accessible, and then you can reference it directly in the inner class.
For example, suppose you have an outer class called OuterClass, and you want to get a reference to that class in the inner class InnerClass. You can do this:

class OuterClass {
    
    
    var name: String? = null
}

class InnerClass {
    
    
    val outer: OuterClass? = null

    fun printOuterName() {
    
    
        outer?.let {
    
    
            println("Name of the outer class: ${
      
      it.name}")
        }
    }
}

In this example, OuterClass is an outer class and InnerClass is an inner class. In InnerClass, we declare an
outer variable, which is a reference to OuterClass. Then, in the printOuterName method, we
access the name attribute of the outer class through the outer variable.

  1. [Essay question] Is the Person below an interface? Why?

class User : Person()

In the code you provided, Person is not an interface, but a class. You are using the Kotlin language, which supports inheritance of interfaces or classes through colon (:).
In this code, the User class inherits the Person class by using:. This means that User is a subclass of Person and inherits Person's properties and methods.
If Person is an interface, it should be declared using interface Person. So in this code snippet, Person is not an interface, it's a class.

Guess you like

Origin blog.csdn.net/weixin_74239923/article/details/134125110