Kotlin's basic grammar, starting to learn Kotlin, can be analogous to the Java language, but can not be fixed by the thinking mode of Java.
1. Guide Pack
Like java, the imports are at the top of the file
package my.demo
import java.util.*
2. Defining Functional Functions
- Functions with Int type return values
fun sum(a: Int, b: Int): Int {
return a + b
}
Execution result: Input 3 and 5 are invoked, return 8
- The expression acts as a function body, and the type of return value is determined automatically.
fun sum(a: Int, b: Int) = a + b
Execution result: Input 3 and 5 are invoked, return 8
- For return value function
fun printSum(a: Int, b: Int): Unit {
println("sum of $a and $b is ${a + b}")
}
Implementation results: sum of-1 and 8 is 7
As you can see, $is similar to string splicing in java, but more readable.
- Unit can omit writing when it agrees that there is no return value like java
fun printSum(a: Int, b: Int) {
println("sum of $a and $b is ${a + b}")
}
Implementation results: sum of-1 and 8 is 7
3. Statement of variables
- constant
In java, declaring constants requires final, while in Kotlin only val is needed, and consent can only be assigned once
val a: Int = 1 // Concurrent assignment of declarations
val b = 2 // Self-inferring data type is Int
val c: Int // When no initial value is provided, the data type needs to be specified
c = 3 // Value assignment after declaration
- variable
Can be assigned multiple times
var x = 5 // Self-inferring data type is Int
x += 1
4. Notes
No difference from java
/**
* Documentation Comments
* @param a
*/
fun add(a: Int) {
/*
multiline comment
*/
println("test")
//Single-Line Comments
var a=2
}
5. Use string templates
Do you remember string splicing in java? For programmers, reading and writing are troublesome, and Kotlin has completely solved this problem.$
var a = 1
// Define a string variable, and the template represents a variable
val s1 = "a is $a"
a = 2
// Using templates to represent an expression,
val s2 = "${s1.replace("is", "was")}, but now is $a"
Output: a was 1, but now is 2
The stitching variable needs to be followed by the name of the variable directly. The stitching expression needs to use {} and the specific value will be obtained in the string.
6. Use conditional expressions
The same thing as java
var max = a
if (a < b) max = b
// With Other
var max: Int
if (a > b) {
max = a
} else {
max = b
}
Unlike java, it can be used as an expression to assign values to variables or methods.
//Variable assignment
fun maxOf(a: Int, b: Int) = if (a > b) a else b
//Variable assignment
var max=if (a > b) a else b
7. Use nullable values
//If this directly assigns a value that cannot be null, it cannot be compiled.
var a:Int
a=null
//Use data types? After that, it can be expressed that the result can be null.
var a:Int?
a=null
The same is true for methods.
Such as:
/**
*The return value can be null
*/
fun parseInt(str: String): Int? {
// ...
}
//Use the above analytical method
fun printProduct(arg1: String, arg2: String) {
val x = parseInt(arg1)
val y = parseInt(arg2)
// Using `x * y` yields error because they may hold nulls.
if (x != null && y != null) {
// x and y are automatically cast to non-nullable after null check
println(x * y)
}
else {
println("either '$arg1' or '$arg2' is not a number")
}
}
8. Type checking and automatic conversion
Use the instance keyword in java to determine whether an object belongs to a class or interface, use is in Kotlin, and the type after checking automatically converts to that type
fun getStringLength(obj: Any): Int? {
if (obj is String) {
// Object obj, within this branch, automatically converts to String type
return obj.length
}
//Outside the branch, the obj object is still Any type
//The return value Int can be null
return null
}
Or in the following form
fun getStringLength(obj: Any): Int? {
if (obj !is String) return null
// Object obj, within this branch, automatically converts to String type
return obj.length
}
Or in the following form
fun getStringLength(obj: Any): Int? {
//The obj object on the right of'&'will also be automatically converted to String type.
if (obj is String && obj.length > 0) {
return obj.length
}
return null
}
It can be said that when the is keyword is used to determine whether an object belongs to a certain type, if so, the object will automatically be converted to the corresponding type.
9. Use the for loop
The for loop traverses anything that provides an iterator. The grammar is listed below.
//A list set
var list = listOf<String>("Hello","not good","very good")
//for loops, the grammar uses in keywords
for (str in list)
//Output the result of each fetch
println("value = $str")
As in java, when there is only one loop statement, you can omit brackets, otherwise you won't omit them.
var list = listOf<String>("Hello","not good","very good")
for (str in list){
println("value = $str")
println(str)
}
If you want to traverse the subscript index of a collection or array, you can use the following method
var list = listOf<String>("Hello","not good","very good")
for (str in list.indices){
println("value = $str")
}
Output results:
value = 0
value = 1
value = 2
If you want to traverse subscripts and values at the same time, you can do this:
var list = listOf<String>("Hello","not good","very good")
for ((index,str) in list.withIndex())
println("index = $index ,value = $str")
Output results
Index = 0, value = Hello
Index = 1, value = bad
Index = 2, value = good
10.while and do... while
Same usage as in java
while (x > 0) {
x--
}
do {
val y = retrieveData()
} while (y != null) // y is visible here!
11.when expression
The switch statement is cancelled in Kotlin and the simplest switch statement is expressed in when.
//Function function that returns a value based on what is passed
fun describe(obj: Any): String =
when (obj) {
1 -> "1"
"Hello" -> "greetings"
is Long -> "Long Type data"
!is String -> "No String Type data"
else -> "Unknown"
}
Is is is used to determine the object type, which is equivalent to instance in java. You can see when can also be converted to if statements
Multiple matching conditions can also be performed, separated by commas.
when (x) {
0, 1 -> print("x == 0 or x == 1")
else -> print("otherwise")
}
Matching conditions can also be a function
when (x) {
parseInt(s) -> print("s encodes x")
else -> print("s does not encode x")
}
Matching conditions can also be a range of values
when (x) {
in 1..10 -> print("x is in the range")
in validNumbers -> print("x is valid")
!in 10..20 -> print("x is outside the range")
else -> print("none of the above")
}
12. Scope of use
To determine whether a number belongs to a certain range, use in keyword.
val x = 4
if (x in 1..10) {
println("fits in range")
}
Judging that a number is not in a certain range
val x = 4
if (x !in 1..10) {
println("not in range")
}
Kotlin's default traversal is ascending order.
for (i in 4 downTo 1) print(i) // prints "4321"
Kotlin defaults to incremental decrement of 1, which can be set using step:
for (i in 4 downTo 1 step 2) print(i) // prints "42"
If you want to indicate that the range does not include the last value, use until
for (i in 1 until 10) { // i in [1, 10), 10 Not included
println(i)
}
Excuse me for the poor translation.