Kotlin basic syntax

Variables and functions (methods) are the two most important types of syntax for a language. Thanks to Kotlin syntax sugar, JVMS that don’t normally support function syntax support putting functions at the top of your code. This article mainly introduces the definition of variables and the basic use of functions.

1. Define variables

Most programming languages have the concept of variables and constants. Kotlin is similar to Java in that, although there is no constant syntax, you can use final to define an unmodifiable variable, which is essentially a constant.

In Java, variables are defined like this:

int a=10; Final double b = 1.0; String s="Hello";
int ok;
Copy the code

In Kotlin, defining variables differs from Java in several ways:

  1. Different placement: In Kotlin, data types are placed after variables and separated by colons (:), the opposite of Java;
  2. Variable constants keyword: in Kotlin variables start with var and constants start with val;
  3. Data type first letter: in Kotlin, all data type first letters are capitalized;
  4. If the variable is not initialized when it is defined, the data type must be specified. If the variable is initialized when it is defined, the Kotlin compiler does not have to declare the data type and deduces the data type from the value to the right of the equal sign.

Take a look at the sample code:

Var a=10 var b:Double=2.0 val c="hello"
var d:Int

d=a
        
c="hi"// The compiler reported an error because c is a constantCopy the code

2. Define the function

No matter what language, the definition of a function must have the following parts:

  1. Function header: includes the function name and keywords that identify the function, such as fun;
  2. Parameter: includes parameter name and parameter type.
  3. Return value: includes return value type;

Kotlin code:

fun add(a: Int, b: Int): Int {
    return a + b
}
Copy the code

As you can see, when defining a Kotlin function, the function header needs to contain the fun keyword in addition to the function name. As for parameters, you define Kotlin variables in the same way. If the function has a return value, the return value type is specified at the end of the function definition section, separated from the function definition section by a colon (:). If the function returns no value, it can return Unit, or nothing at all, as in:

fun add(a: Int, b: Int) {
    a + b
}
Copy the code

3, comments,

Annotations in Kotlin, like annotations in Java, have single-line and block annotations.

/* */ block comment

Kotlin block comments also support nesting:

/* hello /* world */ */

Underlying data types

In Kotlin, everything is an object. Any variable has corresponding methods and attributes. To improve efficiency, Kotlin has optimized some data types to become built-in data types. But these types of variables are used just like normal classes, with their own methods and attributes.

Common data types are numbers, characters, booleans, and arrays.

1. Numeric types

Built-in data types provided by Kotlin:

The data type The number of bytes
Double 8
Float 4
Long 8
Int 4
Short 2
Byte 1

Kotlin code:

Var a: Int = 10 var b: Double = 2.0 val c: Boolean =true
var d: Short = 0
Copy the code

Kotlin, like Java, has default types: Int for integers and Double for floating-point numbers.

However, Java automatically converts a variable with a small number of bytes to a variable with a large number of bytes. Kotlin does not. Kotlin provides a series of methods for type conversions:

  • toByte()
  • toShort()
  • toInt()
  • toLong()
  • toFloat()
  • toDouble()
  • toChart()

Kotlin, like Java, provides special representations for values of the Double and Float types, as well as hexadecimal and binary

  • Represents a value of type Long, followed by L or L, as in 100L
  • Represents a value of type Float, followed by F or F, as in 12.3f
  • Represents a hexadecimal number preceded by 0x, such as 0x1F
  • Indicates that the binary is not preceded by 0b

Kotlin also provides numeric delimiters, delimited by underscores (_), which can be delimited depending on the situation. For example, 1000000 means one million, which can be written as 1_000_000 for easy reading.

2. Character types

In Kotlin, character types are represented by Char, but unlike Java, characters cannot be treated as numbers directly.

Like Java, characters are quoted in single quotes, and Kotlin also supports backslash escapes, such as the common \n, \t, \b, and so on.

Although characters cannot be used directly as numeric values, they can be converted to their corresponding ASCII values using the toInt() method.

3. Boolean types

Boolean types in Kotlin are described by Booleann and have two values: true and false. Boolean type three operations: logical or (| |), logic and non (&) and logic (!) .

Take a look at the following code example:

var flag1 : Boolean =true
val flag2:Boolean= false
if(flag1 && flag2){
	println("true")}if(flag1 || flag2){
	println("false")}Copy the code

4, arrays,

In Kotlin, arrays are described by Array, which contains the get and set methods, the size attribute, and other member methods.

There are many ways to define arrays in Kotlin, using the arrayOf() function to define arrays that can store arbitrary values; Use the arrayOfNulls function to define an empty array of specified length (there are no values in the array elements). Define arrays using the Array class’s constructor to specify the length of the Array and how the data is initialized; Define and initialize an array of the specified type using the functions intArrayOf, shortArrayOf, and so on. Take an example:

Val arr1= arrayOf(1,2) println(arr1[2]) arr1[2]=10 println(arr1[2]) var arr2= arrayOfNulls<Double>(10) Println (arr2.size) var arr3= intArrayOf(1,2,3,4,5) println(arr3[0])Copy the code

5. Strings

Kotlin uses String to represent strings. There are two types of strings:

  1. Ordinary string: Similar to Java, string can be added to escape characters to achieve newline requirements;
  2. Preserve raw format strings: You cannot use escaped strings, the format is displayed directly in the string, and the content is enclosed in three pairs of double quotes.
val s1="Hello\n"
val s2="World"

val s3="""Hello World"""
Copy the code

String template

A very important function of Kotlin is the string template. A string template is a string in which placeholders are added, and the content is specified later, that is, a template can be used to set the dynamic parts of the string.

Templates use dollar signsI “, among themThe following I is a variable and can also be used as a placeholder for ${expression}.

val s1="Hello $arr1[0]. ""
val s2="World ${a+b}"
Copy the code

package

There is also the concept of packages in Kotlin, which are expressed in exactly the same way as in Java, except that packages in Kotlin have no relation to directories. Packages in Kotlin are simply designed to reference resources in files.

package com.example.kotlin

fun adtion() {}

class MyClass {}
Copy the code

The above code, and a class defines a function, in fact, complete the function name and the name of the class were com. Example. Kotlin. Adtion and com. Example. Kotlin. MyClass.

So in other Kotlin file, if you want to use adtion method or the MyClass class, direct call com. Example. Kotlin. Adtion and com. The example. The Kotlin. MyClass.

Of course, for convenience, you can import the file first, as in Java

import com.example.kotlin.adtion
import com.example.kotlin.MyClass
Copy the code

or

import com.example.kotlin.*
Copy the code

Kotlin also supports an alias for imported resources:

import com.example.kotlin.adtion as a
import com.example.kotlin.MyClass as m
Copy the code

The control flow

Kotlin’s control flow is basically the same as Java’s, except that when is used instead of switch. Of course, in Kotlin, if and when can be used not only as statements, but also as expressions.

1. Conditional statements

In Kotlin, the if statement itself is an expression that returns a value, so Kotlin doesn’t have three-wood operators like Java does. Here is the basic use of conditional statements:

if(a<b){
    println(a)
}else{
    println(b)
}
Copy the code

If we use an if statement as an expression, the last statement that satisfies the condition is the return value:

var min=if(a<b){
			println(a)
		    a
	}else{
		    println(b)
		    b
	 }
Copy the code

2. When statement

In Kotlin, when is used instead of the switch statement, as follows:

when (a) {
	1 -> {
		println(1)
    }
    2 -> {
        println(2)
    }
    else -> {
        println("else")}}Copy the code

When using the when statement, note:

  1. The when statement looks for the first branch that meets the criteria based on the value passed in and executes the branch statement.
  2. If there is more than one statement in the branch, use curly braces {};
  3. The when statement is terminated automatically when a branch satisfies the condition, so it is not necessary to add a break to each case statement as in the switch statement.

Of course, the when statement can also be used as an expression, with the return value of the first statement that satisfies the condition:

var m=when (a) {
	1 -> {
		println(1)
    }
    2 -> {
        println(2)
    }
    else -> {
        println("else")}}Copy the code

If multiple branches execute the same code, separate multiple conditions in one branch with commas (,), for example:

when (a) {
    1, 3, 5 -> {
        println(1)
    }
    2, 4, 6 -> {
        println(2)
    }
    else -> {
        println("else")}}Copy the code

Branching conditions in when can be constants as well as expressions, such as:

when (a) {
    in1.. 5 -> { println(1) }in6.. 8 -> { println(2) }else -> {
        println("else")}}Copy the code

3. For loop

In Kotlin, the for loop can enumerate elements in a collection directly or by collection index.

for(item in collection) println(item)
Copy the code
Var arr = arrayOf,4,6,8 (2)for(item: Int in arr){
	println(item)
}
Copy the code
for(i in arr.indices){
	print(arr[i])
}
Copy the code

4. While loop

The while loop in Kotlin is the same as the while loop in Java, which is also divided into while and do.. While, the code looks like this:

var i:Int=0
while(i<10){
	println(i)
    i++
}
Copy the code

In a loop, use “continue” and “break”. “continue” terminates the loop and executes the next loop, and “break” breaks out of the loop and executes the next step, just like in Java.

summary

Although Kotlin and Java are seamless, there are many differences in syntax, most importantly in coding habits and concepts, so it takes some work to fully master Kotlin.

Follow-up content, please pay attention to my wechat public number – Android Motor vehicle