preface
Starting from this article, I will sort out some notes in my study of Kotlin for systematic arrangement of knowledge. The main audience is Android developers, and the article may cover some syntax comparisons with Java, as well as some examples of Android applications.
function
The basic grammar
The way you declare functions in Kotlin is a little different from the way you declare functions in Java, so let’s compare.
//Java
public int add(int a, int b) {
return a + b;
}
Copy the code
//Kotlin
fun add(a: Int, b: Int): Int {
return a + b
}
Copy the code
Here’s a simple example to summarize:
- Used in the Kotlin
fun
Keyword to declare a function - A variable (parameter) is written as
< variable name >: < variable type >
- The return type is used after the parameter list
: < return value type >
said - Kotlin code does not need to be added
;
Other syntactic features of the Kotlin function:
Use = instead of return and {} to simplify code when the function body is only one line long.
Fun add(a: Int, b: Int) = a + bCopy the code
When no value is returned, Java returns void and Kotlin returns Unit, which can be omitted.
//Java
void print(){}
//Kotlin
fun print(): Unit{} // omit Unit funprint() {}Copy the code
A complete Kotlin function declaration looks like this:
< modifier > fun < function name >(< parameter name >: < parameter type >...) Public fun add(a: Int, b: Int): Int {return a + b
}
Copy the code
Kotlin does not add any modifiers, the default permission is public, in class functions are the same as Java public final, cannot be overridden by subclasses.
The default parameters
Arguments in Kotlin can have default values, which can be used to reduce function overloading when the variable is omitted from the call.
Public fun showToast(text: String, time: Long = Toast.LENGTH_SHORT){ Toast.makeText(getApplicationContext(), text, Public void showToast(String text){showToast(text, toast.length_short); } public void showToast(String text, Long time){ Toast.makeText(getApplicationContext(), text, time).show(); }Copy the code
Parameters that have default values must indicate the parameter type.
If a parameter with a default value comes before a parameter with no default value, you cannot omit the parameter with a default value, or use named parameters.
Named parameters
-
When a function has a large number of arguments, using named arguments when passing in parameters can improve code readability. The format is < variable name > = < variable value >.
-
When using named parameters, you can dispense with one-to-one correspondence between positions.
-
Named parameters can omit intermediate parameters that have default values.
-
If there are named parameters, the following parameters must be named parameters; otherwise, the compilation fails.
Variable length parameter
In Kotlin you can use the vararg keyword to indicate variable length arguments to a function.
fun test(vararg list:String) {
for (str in list){
println(str)
}
}
fun main() {
test("one"."two"."three"} // One two threeCopy the code
Lambda expressions (anonymous functions)
I’ll give you a small example and explain it in detail in a later article.
fun main(){
val sumLambda: (Int, Int) -> Int = {x, y -> x + y}
println(sumLambda(2, 3))
}
Copy the code
variable
Variables in Kotlin can be divided into mutable and immutable variables, modified with var and val, respectively.
Var is short for variable
Val is short for value
Volatile variables
Var < variable name >: < type > = < initial value >
Immutable variable
A variable that can only be assigned once, similar to the final modifier in Java.
Val < variable name >: < type > = < initial value >
The compiler supports automatic type inference, which can be declared without specifying a type. The compiler automatically inferred the type from the initial value.
Kotlin’s air safety
In Kotlin, variables are non-null by default, such as when typing the following code in the IDE:
var str: String = null
Copy the code
The compiler will tell you that the compilation failed.
Kotlin’s null-safe design is simply to avoid nullPointerExceptions by using IDE hints to avoid calling NULL objects. Such null-safety limits can avoid many runtime exceptions.
Sometimes we really need nulls, so we can use nullable types. Add one after the type? , such as String? , the View? .
The code above should be changed to:
var str: String? = null
Copy the code
Non-nullable and nullable types are two different types. Like String and String? It’s different.
Type String? A variable of type String cannot be assigned directly to a variable of type String because String? Can be null, but String can not, which is equivalent to narrowing the scope, if you must convert, need to add after!! , indicating that the variable must not be null.
Conversely, a variable of type String can be assigned directly to a variable of type String, right? The variables.
Nullable types do not call the function of a variable directly with. Instead, they use? The safe call, which checks whether a variable is null and then calls a function if it is not, is thread-safe as a language-level rule. Normal plus an if judgment is not thread-safe, so it will not compile. Still usable!! If the variable is null, a NullPointerException will be reported. If the variable is null, asserted call will be reported.
Var name: String = null name.length() // Compilation failedif(name ! = null){name.length()} name? .length() // safe call, run time this statement does not execute name!! .length() //non-null Asserted Call. In the current case, name is null and nullPointerCall is assertedCopy the code
Initialization of a variable
For top-level variables (variables defined directly in the KT file), you must specify an initial value at declaration time or use the lateinit keyword to delay initialization.
var p1 :String = ""Var p2 :String lateinit var p3:String lateinit :String Lateinit :StringCopy the code
For variables defined in a class, you must specify an initial value when declaring them, either as abstract (the class also becomes abstract) or lateInit.
Abstract class p1 {var p1: String // Compiler failed. Property must be initialized or be initialized. Lateinit var p3: String use the lateinit keyword to delay initialization}Copy the code
Local variables in a function can be declared without specifying an initial value, but must be assigned before they are used, otherwise they will compile.
fun mainPrintln (STR) {var STR: String (String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, Stringmain() {var STR: String // no initial value is specified"hello"Println (STR) // compile through}Copy the code
lateinit
The lateInit keyword is used to resolve the situation where a variable cannot be assigned an initial value when it is declared. (For example, in Android development, declaring a control variable must be initialized in the Activity’s onCreate method.) Its purpose is to keep the IDE from checking the initialization of the variable and reporting errors. The initialization of the variable is entirely up to the developer. Lateinit can only modify var, not val.
Top-level attributes and functions (top-level)
In Kotlin, instead of writing attributes and functions in a class, you can write them directly in a KT file. Such attributes and functions are called top-level attributes/functions. The scope of the properties and functions is pakeage.
// Utils class package cc.lixiaoyu. A val p = 0 funprintHello(){
println("hello")}Copy the code
//b package中的Main类
package cc.lixiaoyu.b
import cc.lixiaoyu.a.p
import cc.lixiaoyu.a.printHello
fun main() {
printHello()
println("p = $p")}Copy the code
Top-level attributes and functions in the same package cannot have the same name.
Top-level functions and properties are called in Java code in the form of the class name Kt. The function name. Such as:
public static void main(String[] args) {
UtilsKt.printHello();
System.out.println("p = " + UtilsKt.getP());
}
Copy the code
conclusion
That’s enough for the two most basic Kotlin concepts, functions and variables, and the next article will cover the basic data types in Kotlin.
The resources
Kotlin’s variables, functions, and types
Kotlin basic syntax