Quickly get started with Kotlin from Java, essential pre-knowledge for Android development

1. Basic data types

2. Data container

2.1 Array

//Create an array directly, through arrayOf
    var arrayNum:Array<Int> = arrayOf(1,2,3,4)
    var arrayObjects:Array<Any> = arrayOf(1,true,"1")
    //Create an array through arrayOfNulls, all elements are empty
    val arrayOfNulls = arrayOfNulls<String>(5)
    //Use Array's constructor to dynamically create an array
    val array = Array(5) { i ->  (i * i).toString()  }

    //Create an array with an initial length of 5 and a content of 100
    val arr1= IntArray(5){100}
    //Create an array. The content of the corresponding index is twice the index. it is a proprietary variable that represents the initial subscript.
    val arr2=IntArray(5){it*2}

    //Array traversal operation
    for(item in arr2){
        //print(item)
    }
    //Get the corresponding element based on the subscript
    for (item in arr2.indices){
        //print(arr2[item])
    }
    //Traverse subscripts and elements at the same time
    for((index,item) in arr2.withIndex()){
        println("$index->$item")
    }
    //Traverse through foreach loop
    arr2.forEach {
        //println(it)
    }
    //The enhanced version of foreach can obtain the corresponding subscript and element at the same time
    arr2.forEachIndexed{index, item ->
        println("$index->$item")
    }

2.2 Collection

/**
* list collection
*/
//Variable list, the same is true with arrayListOf
val mutableListOf = mutableListOf<String>()
mutableListOf.add("1")
//immutable list,listOf
val listOf = listOf<Int>(1,2,3)

/**
* map collection
*/
val mutableMapOf = mutableMapOf<String, Int>()
mutableMapOf.put("aihua",1)
mutableMapOf["aihua"]=2

//Specify the initialized elements in the collection through pair
val mutableMapOf1 = mutableMapOf<String, String>(Pair("hello", "world"))
//Immutable map elements
val mapOf = mapOf<String, String>(Pair("key","value"))

/**
* set collection
*/
val mutableSetOf = mutableSetOf<Int>()

val of = setOf<Int>()

3.Method

3.1 Methods of ordinary classes

3.2 Methods of static classes

3.3 Methods of companion classes

package com.sjvave.aihua.basictype

import java.awt.PrintGraphics

fun main(){
    //Call ordinary methods in ordinary classes
    Person().test()
    //Call the method in the companion class directly through the class name
    Person.test02()
    //Call static method through class name
    println(Util.add(1,1))
}

/**
 *Declare methods in ordinary classes
 */
class Person{
    fun test(){
        println("I am the test method in person")
    }
    companion object{
        fun test02(){
            println("I can be called directly")
        }
    }
}

/**
 * Calling methods in static classes
 */
object Util{
    fun add(a:Int,b:Int):Int{
        return a+b
    }
}

3.4 Method parameters

Default parameters

In fact, it means adding an equal sign after the parameter and giving a default value.

named parameters

The situation targeted is: a default parameter is followed by a parameter without a default value, so when calling a method, you must use the (variable name = value) method to assign the value.

There is also the following special situation

package com.sjvave.aihua.basictype

import java.awt.PrintGraphics

fun main(){
    //Calling method one
    test(1,2,action = {
        //The last line in the method body is the return value of the method
         3
    })
    //Calling method two
    test(start = 2){
        3
    }
}

fun test(offset:Int = 0,start:Int,action:() -> Int){
    val res=action()
    print(res)
}

variable number of arguments

package com.sjvave.aihua.basictype

import java.awt.PrintGraphics

/**
 *Points to note:
 * There can only be one parameter marked vararg in a method
 * vararg is not the last parameter. You can use named parameter syntax to assign values ​​to subsequent parameters.
 */
fun main(){
    val append = append('1', '2', '3')
    val charArrayOf = charArrayOf('a', 'b', 'c')
    val append1 = append('a', 'b', *charArrayOf)
    print(append1)
}
fun append(vararg str:Char):String{
    val stringBuffer = StringBuffer()
    for (char in str){
        stringBuffer.append(char)
    }
    return stringBuffer.toString()
}

4.Lambda expression

package com.sjvave.aihua.basictype

import java.awt.PrintGraphics

/**
 *Points to note:
 * When there is only one parameter, you can directly use the implicit parameter it
 */
fun main(){
    val number = arrayOf(1, 3, 4, 5)
    /*transform(number,action = { index:Int,element:Int ->
        index*element
    })*/
    transform(number){index,element ->
        index*element
    }
    for (i in number) {
        println(i)
    }
}
fun transform(array:Array<Int>,action:(Int,Int)->Int){
    for (index in array.indices){
        val newVal = action(index, array[index])
        array[index]=newVal
    }
}

5.Conditional control

package com.sjvave.aihua.basictype

import java.awt.PrintGraphics

/**
 *Points to note:
 * When there is only one parameter, you can directly use the implicit parameter it
 */
fun main(){
    println("maxof:${maxOf(2,4)}")
}
fun maxOf(a:Int,b:Int):Int{
    if(a>b){
        return a
    }else{
        return b
    }
}
fun max0f02(a:Int,b:Int):Int{
    return if (a>b) a else b
}

/**
 * The value in the when brackets is not necessarily a certain value and can be obtained dynamically
 */
fun eval2(number:Number):String=when (number){
    is Int -> "this is Int"
    else -> "invalid number"
}

6. Generics

Generic interface/class

Generic fields

Generic methods

Generic constraints

out and in in generics

package com.sjvave.aihua.basictype

import java.awt.PrintGraphics

/**
 *Points to note:
 * When there is only one parameter, you can directly use the implicit parameter it
 */
fun main(){
    AppleDrink().drink("apple juice")
    BlueColor("blue").printColor()
    formJson("{}", String::class.java)
}

/**
 * Generic interface
 */
interface Drink<T>{
    fun drink(t:T)

}
class AppleDrink :Drink<String>{
    override fun drink(t: String) {
        print("I'm drinking ${t}")
    }
}

/**
 * Generic class
 */
abstract class Color<T>(val t:T/*generic field*/){
    abstract fun printColor()
}
class BlueColor(val color:String):Color<String>(color){
    override fun printColor() {
        println("color:${color}")
    }

}

/**
 * Generic methods
 */
fun <T>formJson(json:String,tClass:Class<T>):T?{
    val t:T?=tClass.newInstance()
    return t
}
/**
 * Generic constraints
 * Constraints on generics can only be the corresponding type or its subclass (single constraint)
 */
fun <T:BlueColor>formJson02(json:String,tClass:Class<T>):T?{
    val t:T?=tClass.newInstance()
    return t
}
/**
 * Generic constraints
 * Multiple constraints
 */
fun <T>formJson03(json:String,tClass:Class<T>):T? where T:Comparable<T>,T:Number{
    val t:T?=tClass.newInstance()
    return t
}

/**
 * Use of out and in keywords
 */
open class Animal
open class Dog:Animal()
fun animalFuns(){
    val animal:Animal=Dog()
    //After using the out keyword, the following error will not be reported, because the collection type of kotlin will not actively perform forced transfer.
    //This is where the out keyword is used
    val animalList:ArrayList<out Animal> = ArrayList<Dog>()

    //On the contrary, this represents the lower limit of the type, allowing it to be passed in itself or its parent class
    val animalList02:ArrayList<in Dog> = ArrayList<Animal>()

}
//Use the out keyword at the definition
class ArrayList<out T>{

}

7.Extension functions

Extension method (extension of a class that does not exist)

package com.sjvave.aihua.basictype

import java.awt.PrintGraphics

/**
 *Points to note:
 * When there is only one parameter, you can directly use the implicit parameter it
 */
fun main(){
    //Ikun().rup()
    val mutableListOf = mutableListOf<Int>(1,2,3,4)
    mutableListOf.swap(0,2)
    mutableListOf.forEach{
        print(it)
    }
    var myString="android"
    val lastChar = myString.lastChar
    println(lastChar)
    tesApply()
}

class Is
    fun test(){

    }
}
fun Ikun.rup():String{
    return "ge ge rap"
}
//Extension method
fun <T> MutableList<T>.swap(index:Int,index2:Int){
    val temp=this[index]
    this[index]=this[index2]
    this[index2]=temp
}
//no
val String.lastChar:Char get() = this.get(length-1)

//Some built-in extensions let, run, apply
//A question mark is added after the class, which means that the parameters can be empty, that is, there is a null operation.
fun testLet(str: String?){
    //If the corresponding one is empty, the logic inside will not be executed, and the last line is the return value.
    str?.let {
        //This property cannot be accessed outside the scope
        val str2="android"
        print(str2)
    }
}
//run extension function
fun textIs(is: Is){
    ikun.run {
        //You can directly access the public properties and methods of the instance, and the last line is the return value
        test()
    }
}
//apply extension, the return value is itself, which is a little different from run, run returns the last line
fun tesApply(){
    ArrayList<String>().apply {
        add("11")
        add("33")
    }.run {
        for (s in this){
            println("apply:${s}")
        }
    }
}

8. Make a simple binary arithmetic operator

package com.sjvave.aihua.basictype

import java.lang.Exception

fun main(){
    while (true){
        println("Please enter your expression:")
        val input= readLine()
        try {
            //Only perform calculations when it is not empty
            input?.let {
                val res=cacalate(it)
                println("${input}=${res}")
                println("Do you want to continue using (y/n)")
                val cmd= readLine()
                cmd?.let {
                    if(it.equals("n")){
                        System.exit(-1)
                    }else{

                    }
                }
            }
        }catch (ex:Exception){
            ex.printStackTrace()
        }
    }
}

fun cacalate(input: String): String {

    if(input.contains("+")){
        val numbers = input.trim().split("+")
        return operate(numbers[0].toDouble(),numbers[1].toDouble(),"+").toString()
    }else if(input.contains("-")){
        val numbers = input.trim().split("-")
        return operate(numbers[0].toDouble(),numbers[1].toDouble(),"-").toString()
    }else if(input.contains("*")){
        val numbers = input.trim().split("*")
        return operate(numbers[0].toDouble(),numbers[1].toDouble(),"*").toString()
    }else if(input.contains("/")){
        val numbers = input.trim().split("/")
        return operate(numbers[0].toDouble(),numbers[1].toDouble(),"/").toString()
    }
    return "error please input you numbers"
}

fun operate(num1: Double, num2: Double,operate:String): Double {
    return when(operate){
        "+" -> num1+num2
        "-" -> num1-num2
        "*" -> num1*num2
        "/" -> num1/num2
        else -> 0.0
    }
}


Guess you like

Origin blog.csdn.net/2301_76875881/article/details/131934333