kotlin tutorial (1)

[TOC]
Recently I am reading "kotlin combat". I will take some notes here, which should be reviewed and summarized. At the beginning, I will attach the address of the official website document https://www.kotlincn.net/
This document mainly describes the basic elements of kotlin, variables , functions, classes, etc.

functions and variables

Hello World starts

public class First{
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}

The code in kotlin is much simpler

// kotlin默认的返回值就是Unit,即对应Java中void方法,所以下面两行的写法是等价的
// fun main(args: Array<String>): Unit {
fun main(args: Array<String>) {
    printlin("Hello World)
}

From these two pieces of code, we can know that

  • Make a function with the keyword fun
  • The type life of the parameter is after the name, and the same is true for the declaration of the variable, eg. val a:Int = 10 (declare a variable of type Int with a value of 10)
  • Functions can be defined in the outermost layer and do not need to be placed in a class
  • Arrays are classes, kotlin has no special syntax for declaring array types, ie args:Array
  • Use println() which is a function in the kotlin standard library (which provides many more concise wrappers than Java syntax) instead of System.out.println();
  • Semicolons can be omitted at the end of the line

function

The above function does not return any value. If you need to return a meaningful result, you need to declare the return type after the method, as follows

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

There is no ternary operator in kotlin, you can use the above if else statement instead. If in kotlin is a bit different from if in Java, in kotlin, if is an expression, not a statement
** The difference between a statement and an expression is that an expression has a value and can be used as part of another expression is used, while the statement has no value of its own

The above function can be written more simply because the function body has only a single expression. So it can be written as
kotlin fun max(a: Int, b: Int) = if (a > b) a else b // 这边因为可以从函数体中推断出返回的值为Int,所以也可以省去返回类型kotlin
. There are many operations in kotlin that can be written out through type deduction, which we will encounter later.

variable

Declaring variables in kotlin starts with the val and var keywords, then the variable name, and finally the type (or not)

val str = "hello"
// 下面两行是等价的
var a:Int = 10
var a = 10
// 如果变量没有被初始化,则必须指定类型,如下所示
val b:Int
b = 22

val -> immutable reference, corresponding to java's final variable
var -> variable reference, corresponding to ordinary variables in java. It
should be noted that although the var keyword operates a variable to change its own value, the type cannot be changed, the same as java , is strongly typed.

var num = 10
num = "ffff"      // 错误,无法通过编译,类型不匹配

classes and properties

class in kotlin

/*java*/
public class Person{
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Implementing the above code in kotlin only takes one line

class Person(var name:String)

或者可以写成下面这种类似java的写法

class Person{
    //默认实现了 getter 和 setter 方法
    var name:String = "我必须初始化" // 类中声明的属性必须得初始化,否则编译报错
}

We can use the kotlin decompilation that comes with idea to see what the decompiled bytecode looks like.

public final class Person {
   @NotNull
   private String name;

   @NotNull
   public final String getName() {
      return this.name;
   }

   public final void setName(@NotNull String var1) {
      Intrinsics.checkParameterIsNotNull(var1, "<set-?>");
      this.name = var1;
   }

   public Person(@NotNull String name) {
      Intrinsics.checkParameterIsNotNull(name, "name");
      super();
      this.name = name;
   }
}

It looks familiar now

  • The default visibility modifier in kotlin is public, and the default class cannot be inherited. If it can be inherited, the open keyword must be added, eg. open class Person{}
  • In kollin, you can use data class XX{} to generate a pojo. Compared with no data, there will be more methods such as toString and hashCode

Attributes

The full syntax for declaring a property is
var

Attributes are defined in kotlin, val will generate getter methods, var will generate setter and getter methods, of
course, we can also define our own

class Square(var height: Int, var width: Int) {

    val isEqual: Boolean
        get() {
            return height == width
        }
}

Guess you like

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