"Kotlin in action" - functions and variables

function

Start with a classic example: Hello World. Let's write a function that prints out Hello World:

fun main(args: Array<String>) {
    println("Hello World!")
}

From this function we can observe the following points:

  • Kotlin uses the keyword fun to define functions
  • The type of the parameter is written after the name
  • The definition of the function can be in the outermost layer of the file, there is no need to put it in the class
  • a class of arrays
  • Use println instead of System.out.println. The Kotlin standard library provides many syntactical brief wrappers around the Java standard library
  • Omit semicolon at end of code

The above function has no return value. If we need to define a function with a return value, what should we do?

fun main(args: Array<String>) {
    println(max(2,3))
}

fun max(a: Int, b: Int): Int {
    return if (a > b) a else b
}

Use the keyword fun to define a function, input two parameters, the parameter is followed by the return value type we need, separated by:. Therefore, from the above two examples, we can basically summarize the basic format of Kotlin functions:

fun 函数名称(参数名称:参数类型):返回值类型 {
    函数体
}

Expression function body

Did you notice the if expression above. In Kotlin, if is an expression, not a statement. So what is the difference between an expression and a statement? The difference between an expression and a statement is that an expression has a value and can be used as part of another expression, while a statement always surrounds the top-level element in the block of code it encloses and has no value of its own. In Java, all control structures are statements, while in Kotlin, except for loops (for, while, do/while), most control structures are expressions.

On the other hand, assignment operations in Java are expressions, but in Kotlin they are all statements. This helps avoid confusion between comparison and assignment.

So, what is an expression function body? We can rewrite the above function to look like this:

fun max(a: Int, b: Int): Int = if (a > b) a else b

As you can see, its function body consists of a single expression, which can be used as a complete function body, with curly braces and return statements removed. If the function unloads curly braces, we say the function has a block body; if it returns an expression directly, it has an expression body.

We can also further simplify the above function:

fun max(a: Int, b: Int) = if (a > b) a else b

As you can see, we omitted the return type. Why can the return value type be omitted here? As a statically typed language, doesn't Kotlin require that every expression should have a type at compile time? In fact, every variable and expression has a type, and every function has a return type. But for an expression-body function, the compiler parses the expression as the function's body and uses its type as the function's return type. This analysis is often referred to as type deduction.

variable

The definition of a Kotlin variable starts with the keyword, then the variable name, then the type, then the variable value:

val min : Int = 20

Of course if the variable is already initialized, we can omit the type:

val min = 20
val question = "May I help you?"

Like the expression body function, if the variable type is not specified, the compiler will parse the initialization value and use its type as the variable type. If the variable is not initialized, an explicit named type is required

var answer : Int

keywords

  • val: Immutable reference. A variable declared with val cannot be reassigned before initialization
  • var: mutable reference. The value of such a variable can be changed.

Although the val reference itself is immutable, the object it points to may be mutable, for example:

val languages = arrayListOf("Java")
languages.add("Kotlin")

The var keyword allows a variable to change its value, but its type cannot be changed. For example, the following code will compile with an error:

var min = 20
min = "min"

string template

Just look at one of the following expressions:

val name = if (!args.isEmpty()) args[0] else "Kotlin"
println("Hello $name!")

This expression introduces a new feature: character creation templates. Like many scripting languages, Kotlin lets you reference local variables in string literals by simply prefixing the variable name with symbol No Such as fruit need want Make use characters, which need to be escaped:

println("\$x")

We can also use more complex expressions that are not limited to variable names, in this case we need to use curly braces to enclose the expression:

println("Hello ${if (!args.isEmpty()) args[0] else "Kotlin"}!")

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324944856&siteId=291194637