The last article focused on constants and variables, functions, and Lambda expressions in Kotlin. This article focuses on class members, operators, statements, and expressions.

Members of the class

Includes properties and methods.

Attributes: Also known as member variables, are variables within the scope of a class

Methods: that is, member functions, class-scoped functions

Member functions are written exactly the same as ordinary functions.

Fun main (args: Array < String >) {cat (" 10 kg ", "orange", "orange clouds day"). } class cat (weight :String, color :String, pattern :String){fun dance (name:String){println(" cat dance $name")}}Copy the code

In constructor arguments, val and var modify math, and classes can define attributes inside, called member variables

Class cat (weight :String, color :String, pattern :String){var catName:String = "fat" {// This is the member variable fun dance (name:String){println(" cat dance $name") }}Copy the code

Attribute access control:

Property can define getters, setters, for example:

Class cat (weight :String, color :String, pattern :String){var catName:String = "fat" get() = field //get (value){field = value} //set fun to dance (name:String){println(" cat jump $name")}} fun main(args: Array<String>) {var catName = cat ("10kg"," orange "," orange cloud ")Copy the code

Properties should be initialized as much as possible in constructors, and if they cannot be initialized in constructors, try to degrade to local variables

The lateinit keyword is used to tell the compiler that we need to delay initialization.

class ABC{
    lateinit var b:String
}
Copy the code

For val, use by lazy so that the instance is not initialized until it is used

class D

class ABC{
    lateinit var b:String
    val d:D by lazy { 
        D()
    }
}
Copy the code

D is not initialized when ABC is initialized. It is only initialized when D is used that an instance of d is returned

The operator

Operators in Kotlin are not that different from Java, but operators in Kotlin support overloading.

Let’s say we override a “+” as the complex operator

fun main(args: Array<String>) {val c1 = Complex(1.0,2.0) val c2 = Complex(4.0,5.0) println(c1 + c2)} class Complex(var) Real :Double,var imaginary:Double){operator fun plus(other:Complex):Complex{// keyword operator return Complex(real +) other.real,imaginary + other.imaginary) } override fun toString(): String { return "$real + ${imaginary}i" } }Copy the code

Results:

5.0 + 7.0 I

In Kotlin, any class can define or override the basic operator of its parent class, defined by the named function corresponding to the operator (such as “plus” for “+”).

The number of parameters is required, but the type of parameter and return value is not required.

Of course, Kotlin doesn’t define arbitrary operators like Scala does

expression

Infix expression

A function that takes only one argument and is modified with infix, somewhat like a custom operator

For example, we have the in operator, which can determine whether an element is in a set. For example:

if (3 in 1.. 10) indicates whether 3 is in the range of [3, 10]

Let’s define an expression to determine if a book is on the shelf:

fun main(args: Array<String>) {

    if (Book() on Desk()){

    }
}

class Book{
    infix fun on(any:Any):Boolean{
        return false
    }
}

class Desk
Copy the code

Branching expression

if .. else.. Expressions are much the same as Java

If (a == b)… else if (a == c) .. else..

But Kotlin is more flexible in that the expression can return the last sentence of each branch, for example:

var a:Int a = if (3 in 1.. 10){ println("true") 1 }else{ println("false") 2 }Copy the code

But in this case, the expression has to be complete,

Something like val x = if(a < 0) 0 is an error, missing an else branch

When the expression

Equivalent to the enhanced switch, which supports any type and conditional branching of pure expressions (similar to if)

Here are a few examples of how to use it:

val state:Int = 3 when(state){ 1 -> println("1") 2 -> println("2") else -> println("3") } when(state){ is Int -> println("is Int") in 1.. 100 -> println(" in [1,100]")! in 1.. 100 -> println("not in [1,100]") 1 -> println(" == 1")} val status = when{2 == 3 -> 1 1 in 2.. 100 -> 3 else -> 4 }Copy the code

Looping statements

There’s nothing special about loops in Kotlin except for (), while(), do.. While () these.

It’s just that the for statement is much cleaner than Java, for example

Println (I)} for(I in IntList){println(I)}Copy the code

No need to judge the number of loops based on the list size.

Here’s one more advantage over Java.

In Java, breaking out of a multi-level loop can be tricky. In Kotlin, you can name a for loop to specify exactly which loop to break out of:

Outter@for(i in 1.. 100){ Inner@for (j in 100.. 1000){ break@Outter }Copy the code

A few other tips

Named parameter:

It is essentially attaching parameters to the arguments of a function

fun plus(arg1:Int,arg2:Int):Int{ return arg1 + arg2 } fun main(args: Array<String>) {plus(arg2 = 1,arg1 = 3) // Specify the first and second arguments}Copy the code

Variable length parameter:

A parameter can receive multiple values and may not be the last parameter. In this case, ambiguous parameters may be passed and a named parameter must be used

fun hello(vararg ints:Int,name:String){ ints.forEach { println(name + it) } } fun main(args: Array<String>) {hello(1,2,3,5,name = "wo")}Copy the code

Default parameters:

You can specify default values for arguments in any position. In case of ambiguity, use named arguments

Fun hello(vararg ints:Int,name:String = "piglet "){ints. ForEach {println(name + it)}} fun main(args: Array < String >) {hello,2,3,5 (1)}Copy the code

This article will mainly cover some structural issues, including expressions, statements, operators, class members, etc. The next article may cover object-oriented topics, including inheritance, overloading, extended members, property brokers, etc., or higher-order functions as appropriate.

If you like, please click 😝