当前位置:网站首页>Kotlin Foundation

Kotlin Foundation

2022-06-25 09:52:00 seevc

This text mainly records Kotlin Basic knowledge of and Java Compare the differences .

1、 Basic variable type and value range

  • Byte Stored value range Integers -2^8 ~ 2^8 -1, namely -128 ~ 127;
  • Short Stored value range Integers -2^16 ~ 2^16 -1, namely -32768 ~ 32767;
  • Int Stored value range Integers -2^32 ~ 2^32 - 1, namely -2147483648 ~ 2147483647;
  • Long Stored value range Integers -2^64 ~ 2^64 - 1, namely -9223372036854775808 ~ 9223372036854775807;
  • Float Stored value range decimal , The decimal point can be accurate to 6 position ;
  • Double Stored value range decimal , The decimal point can be accurate to 15 ~ 16 position ;
  • String Stored value range character string use “” Strings enclosed in double quotation marks can be stored ;

2、 Null processing

stay kotlin Variables defined in are not allowed to be empty , If you want to allow null variables, you need to add... After the type "?", Such as :var str:String? = null

class NullDemo {
    // Parameter is not allowed to be null
    fun noneNullTest(s : String){
        println(s)
    }

    // The parameter is allowed to be null
    fun canNullTest(s:String?){
        println(s)
    }
}

The related operators are : Security call operators (?.) Non empty assertion operators (!!.)
What these two operators do :
?.: When calling the method of this variable , Variable is null Time code stop , Otherwise, the method is called normally ;
!!.: When calling the method of this variable , Variable is null when , Still carry on , At this time, the null pointer exception will be thrown ;

// The parameter is allowed to be null
fun canNullTest(s:String?){
    println(s)

   //s by null, Stop executing 
    s?.capitalize()
   //s by null, Throw exceptions 
    s!!.capitalize()
 }

3、when expression

a. No return value

/**
 *  Having no return value when expression 
 */
fun noneReturn(type:Int){
    when(type){
        1 -> {// Multiple lines of code 
            println(" There are multiple lines of code , Parentheses ")
            println(" There are multiple lines of code , Parentheses ")
        }
       2 -> println(" There's only one line of code , No braces ")     // There's only one line of code , No braces 
       else -> println(" Other situations ")
    }
 }

b.when Expression has a return value

/**
 *  With return value when expression 
 */
fun withReturn(type:Int){
     var str = when(type){
       1 -> {// Multiple lines of code 
           println(" There are multiple lines of code , Parentheses ")
           println(" There are multiple lines of code , Parentheses ")
           " I am a type=1 The return value of "
       }
       2 -> " I am a type=2 The return value of "     // There's only one line of code , No braces 
       else -> " I am the return value of other cases "
    }
    println(str)
}

4、kotlin Medium loop and Range

  • 1 … 100 From 1 To 100, Section :[1,100];
  • 1 until 100 From 1 To 100, Section :[1,100), barring 100;
  • step , step , That is, the step size of the next cycle jump
    fun loopAndRange(){
        var nums = 1 .. 16
        // Will be output 1 2 3 ... 16
        for (n in nums){
            println(n)
        }
        
        var nums2 = 1 until 16
        // Will be output 1 2,3 ... 15, No output 16
        for (n in nums2){
            println(n)
        }
        
        // Will be output 1 3 5 7 9 11 13 15
        for (n in nums step 2){
            println(n)
        }
    }

5、list Basic use

in the light of list A simple cycle

    fun myList(){
        val lists = listOf<String>("1","2","3","4")
        // ordinary for loop , Query list data 
        for (item in lists){
            println(item)
        }
    }

Query by index value list

// Query by index value 
fun myList2(){
    val lists = listOf<String>("1","2","3","4")
    // Bitwise circular query , Include indexes and values 
    for ((i,v) in lists.withIndex()){
        println("$i,$v")
    }
}

###6、map Basic use of
And java identical , Stored key-value Key value pair
The sample code is as follows :

class MapDemo {

    fun mapTest():Unit{
        var map = HashMap<String,String>()
        map["1"] = "hello"
        map["2"] = " "
        map["3"] = "world"

        // Query a key Corresponding value 
        println("map[\"3\"] = ${map["3"]}")

        // Inquire about map All key value pairs in 
        for (kv in map){
            println("key=${kv.key},value=${kv.value}")
        }
    }
}

7、 Functions and function expressions

Function writing example code

class FunctionDemo {

    // Mode one : Method definition 
    fun method(){
        println(" Mode one : Method definition ")
    }

    // Method 2 : If there is only one line of code in the method , Braces can be omitted , as follows 
    fun method2() = println(" Method 2 : If there is only one line of code in the method ")

    fun method3(){
        // Method 3 : Define directly in the method , The form of a function expression 
        var i = {x:Int,y:Int -> x+y}
        var ret = i(1,2)
        println(ret)

        // Method four : It is a perfect way to write method three 
        var j:(Int,Int)->Int = {x,y -> x+y}
        //j Use as a function 
        var retJ = j(1,2)
        println(retJ)
    }
}

8、 Function parameter default values and named parameters

stay kotlin Function parameters in support of setting default values

// Function default 
fun area(pi:Float=3.1415f,r : Float) : Float{
    println(" Calculate the circumference of a circle ----")
    return 2 * r * pi
}

How to use functions with parameters and default values :

  • Do not use the default value of the parameter , In this way area(3.14f,10f) Call function
  • Use default values for parameters , You must use a named parameter , That is, the name of the parameter to be set in the parameter , Such as :area(r=10f), That is, the name of the parameter to which the value is to be passed

9、 Conversion between string and number

Number to string

var a = 30
println(a.toString())

String to number

var a = "30"
val b = a.toInt()

10、 And = Compare

Kotlin Used in Compare two strings to see if they match , use = Compare whether two variables point to the same object on the memory heap ( Address ).

Java in == Make a reference comparison ,equal Compare values

###11、 Console input
Input from the keyboard using :readLine()

fun inputTest(){
    print(" Please enter a number :")
    // Enter content from the keyboard , Assign a value to num Variable 
    var num = readLine()
    println()
}

###12、kotlin Exception handling mechanism in
stay kotlin Exception handling mechanism and java identical , It also uses try...catch form .

class ExceptionDemo {
    // Exception capture mode 
    fun exceptionTest(){
        val str = "aaa"
        try {
            var num = str.toInt()
        }catch (e:Exception){
            println(" Type conversion exception ")
        }finally {
        }
    }
}

Custom exception , Define a class Inherited from Exception, The following example :

class CustomException(string: String):Exception(string)

13、 Tail recursion optimization in recursion

stay java Stack overflow is often encountered in recursive computation in , stay kotlin This problem is also encountered in , But you can use keywords tailrec Are identified
notes : Yes tailrec Recursive functions identified by keywords ,return This recursive function should also be used wherever possible

// Before calculation n Sum of terms 
// keyword tailrec Is the identification of tail recursive optimization 
tailrec fun sum( n:Int,result:Int):Int{
    if(n == 1) {
        return result+1
    }else{
        // Tail recursive optimization ,return  Value must be a recursive method , Do not for :return n+sum(n-1,result)
        // Otherwise the editor will prompt :A function is marked as tail-recursive but no tail calls are found
        return sum(n-1,result+n)
    }
}

14、 Null merge operator ( ?: )

kotlin Hollow merge operator (?:) Has a similar effect Java The conditional expression in .
Such as :var str = a ?: b
What does this sentence mean : When variables a Not for null when , take a Assign a value to str; When variables a by null when , Put the variable b Assign a value to str

15、Double turn Int

1. Transfiguration
println(8.12345.toInt())
Output :8
2. Transfiguration , The way of rounding
println(8.62345.roundToInt())
Output :9
3. Keep the specified decimal places ( Will round off )
var s = “%.2f”.format(8.16678)
println(s)
Output :8.17


Welcome to leave a message for us to exchange and learn from each other !


Sample source address kotlin_demo

原网站

版权声明
本文为[seevc]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202200547583063.html