[kotlin] kotlin's basic grammar

Posted by arimakidd on Fri, 14 Jan 2022 21:31:43 +0100

kotlin learning - basic grammar

1. Introduction

Compare java

1. Simple syntax and less code

2. Advanced Grammar

3. Language security. Eliminate null pointers

4. 100% compatible with Java

2. Operation

Online website: https://play.kotlinlang.org/

val immutable = final

var non final

var a =10

(automatic derivation type)

No semicolon

Variable delay assignment:

var a: Int a=10

function

import kotlin.math.max



fun main(){
    var a=10
    var b=12
    var max=largerNumber(a,b)
    println(""+max)
}
fun largerNumber(num1:Int ,num2:Int):Int {
    return max(num1,num2)

}

Grammar sugar

When a function has only one line of code, Kotlin It allows us to write a unique line of code at the end of the function definition without writing the function body, and connect it with an equal sign in the middle.

Fun largernumber (num1: int, num2: int): int = max (num1, num2) auto derivation – > simplified

fun largerNumber(num1:Int ,num2:Int) = max(num1,num2)

3. Logic control

Program execution statements are mainly divided into three kinds: sequential statements, conditional statements and circular statements

1.if conditional statement

fun largerNumber(num1:Int ,num2:Int):Int {
    var value=0
    if(num1>num2){
        value=num1
    }else{
        value=num2
    }
   return value
}

It needs to be re assigned, so var is used

The kotlin if statement has a return value

So simplify

fun largerNumber(num1:Int ,num2:Int):Int {
    val value=if(num1>num2){
        num1
    }else{
        num2
    }
   return value
}

No re assignment is required, so val is used

Simplify alternative value

fun largerNumber(num1:Int ,num2:Int):Int {

   return if(num1>num2){
       num1
    }else{
        num2
    }
}

Add grammar sugar and simplify it

fun largerNumber(num1:Int ,num2:Int)=if(num1>num2){
       num1
    }else{
        num2
    }

Grammar sugar combined with if grammar

fun largerNumber(num1:Int ,num2:Int)=if(num1>num2) num1 else num2

2.when conditional statement

Similar to switch

Accurate matching

    fun main(){
    val a="Tom"
    println(""+getScore(a))
}
fun getScore(name:String)=when(name){

   "Tom"->86
   "Jim"->77
   "Jack"->95
   "Lily"->100
    else -> 0
}

Type matching

Parameter of type Number

For example, Int, Long, Float, Double and so on are all subclasses related to numbers

fun main(){
    val a=98
    println(""+checkNumber(a))
}
fun checkNumber(num:Number)=when(num){

   is Int -> println("number is Int")
   is Double -> println("number is Double")
   else ->println("number not support")
}

Without parameters

fun main(){
    val a="Tom"
    println(""+getScore(a))
}
fun getScore(name:String)=when{

   name== "Tom"->86
   name=="Jim"->77
   name=="Jack"->95
   name=="Lily"->100
    else -> 0

}

Use startsWith to judge all people beginning with Tom

fun main(){
    val a="Tomkvj"
    println(""+getScore(a))
}
fun getScore(name:String)=when{

   name.startsWith("Tom") ->86
   name=="Jim"->77
   name=="Jack"->95
   name=="Lily"->100
    else -> 0

}

Circular statement

while loops are the same as java

for

For in kotlin

..Closed interval

fun main(){
    for(i in 1..10){
        println(i)
    }
}

until left closed right open section

fun main(){
    for(i in 0 until 9){
        println(i)
    }
}

Step skip some numbers (addition) i+2 == step 2

fun main(){
    for(i in 0 until 3 step 2){
        println(i)
    }
}

output

0

2

Down to descending order

fun main(){
    for(i in 3  downTo 1){
        println(i)
    }
}

output

3

2

1

4. Object oriented

Classes and objects

new instance creation is not required

var p=Person()

Inheritance and constructor

In kotlin, any non abstract class cannot be inherited by default

, which is equivalent to the declaration of final in java

(reason: classes, like variables, should be immutable. If they are variable, there is an unknown risk.)

Abstract keyword open

Inheritance: (extensions in java, colon in kotlin:) parent class with parentheses

Primary and secondary constructors

primary constructor

Each class has a default main constructor without parameters. Of course, you can also explicitly specify parameters. The main function has no function body and can be defined directly after the class name

class Stduent(val sno:String,val grade:Int) : Person()  {
}

Indicates that the required parameters must be passed in when instantiating Student

init function body

class Stduent(val sno:String,val grade:Int) : Person()  {
    init {
        println("sno is"+sno)
        println("sno is"+grade)
    }
}

instantiation

val stduent=Stduent("123",5)

The main constructor calls the constructor of the parent class

1. The parent class has no parameters

Use parentheses

2. The parent class has parameters

Parent class

open class Person(val name:String,val age:Int){
}

Subclass

class Stduent(val sno:String,val grade:Int,name:String,age: Int) : Person(name,age)  {
    init {
        println("sno is"+sno)
        println("sno is"+grade)
    }
}

Add parameters to the main constructor

instantiation

`       val stduent=Stduent("123",5,"123",2)`

Secondary constructor

ktolin stipulates that when a class has both primary and secondary constructors, all secondary constructors must call the primary constructor (including indirect calls)

class Stduent(val sno:String,val grade:Int,name:String,age: Int) : Person(name,age)  {
    constructor(name: String,age: Int):this("",0,name,age){

    }
    constructor():this("",0);
}

The secondary constructor is defined by the constructor keyword,

Here we define two kinds of secondary constructors,

1. The first secondary constructor accepts the name and age parameters, then calls the primary constructor through the this keyword, and assigns the sno and grade parameters as initial values

2. The second function does not accept any parameters. It calls the first constructor defined by us through the keyword this, and assigns the name and age parameters to the initial values,

It is legal because the second secondary constructor indirectly calls the primary constructor

Then there are three instantiation methods

...

kotlin * * * * special case - only secondary constructor, no primary constructor

class Stduent : Person{
    constructor(name: String,age: Int):super(name,age){

    }

}

The secondary constructor directly calls the constructor of the parent class

5. Interface

Interface class

interface Study {
    fun readBooks()
    fun doHomework()
}

Parent class

open class Person(val name:String,val age:Int){
}

Subclass

class Stduent(name: String,age: Int) : Person(name,age),Study{


    override fun readBooks() {
     println(name+"is reading")
    }

    override fun doHomework() {
        println(name+"is donging homework")


    }

}

Main function

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val stduent=Stduent("123",5)
        doStudy(stduent)

    }
    fun doStudy(study: Study){
        study.readBooks()
        study.doHomework()

    }
}

Because the subclass implements the Study interface, it can directly pass the instance of student class - Interface oriented programming, polymorphism

Allows default implementation of functions defined in an interface

– that is, it can not be realized

6. Visible modifier

difference

protected

The current class and subclasses are visible

java: visible in package

internal: the first mock exam is visible in the same module.

7. Data class

data keyword

val user1=User("Xiao Xu",20)
        val user2=User("Xiao Xu",20)

Add data, compare the object properties, return true, and return false without data

8. Singleton class

object keyword

object Singleton {
    fun SingletonTest(){
        println("singletonTest is called")
    }
}

Topics: Android kotlin