当前位置:网站首页>Kotlin language features

Kotlin language features

2022-06-24 13:35:00 Hua Weiyun

@[TOC](kotlin Linguistic characteristics )


Preface

Any language has its own characteristics , Understand the features , In order to study deeply


1、 Nullability characteristics

// kotlin  When declaring parameters , The default is non nullable type .    var name: String = "tiger"// name = null  If the assignment is null  Will be an error ,  Can be assigned as   Empty string  ""        println(name)    //  But in our statement , Use  ?  Specify as nullable type     var name2: String ?    name2 = null    name2 = "tiger"    println(name2)

2、 Security call operators

    var name: String ?    name = "tiger"    name = null// name  It's a nullable type , May be null  Want to use name, Remedial measures must be given , stay name Add later  ?  Symbol // name  It's a nullable type   If it is null,? The following code doesn't execute , No null pointer exception will be thrown    val str = name?.capitalize()    println(str)

3、 use let Security call for

   var name: String? = null    name = "tiger"    name = ""// name  It's a nullable type , May be null  Want to use name, Remedial measures must be given , stay name Add later  ?  Symbol // name  It's a nullable type   If it is null,? The following code doesn't execute , No null pointer exception will be thrown    val str = name?.let {//  If you can get in here ,it  It must not be for null       if (it.isBlank()){    // isBlank name It's an empty string  ""  No content            "Default"       }else{           " I am a :$it"       }   }    println(str)

4、 Non empty assertion operators

    var name: String? = null// name  It's a nullable type , May be null  Want to use name, Remedial measures must be given , stay name Add later  ?  Symbol     name = "tiger"// !!  Assertion operators , and Java equally , Regardless of name  Is it empty , Will go back to the code //  If there is no guarantee name  Assigned , There will be a collapse     val str = name!!.capitalize()    println(str)

5、 contrast if Judge null It's worth it

    var name: String? = null// name  It's a nullable type , May be null  Want to use name, Remedial measures must be given , stay name Add later  ?  Symbol     if (name != null){     // if  It's also a remedy , The code will automatically recognize ,  and Java equally         val str = name.capitalize()        println(str)    }else{        println("name is null")    }

6、 Null merge operator

    var name: String? = "tiger"    name = null    // ?:  Null merge operator ,  If name  be equal to  null , Will execute  ?:  The back area     println(name ?: " So you don't have a name ")    // let  function  +  Null merge operator     println(name?.let { "$it" ?: " So you don't have a name " })

7、 Exception handling and custom exception

    try {        var name: String? = null        checkException(name)        println(name!!.capitalize())    }catch (e: Exception){        println(" Ah , On business again  $e")    }fun checkException(name: String?) {    name ?: throw CustomException()}//  Custom exceptions class CustomException : IllegalArgumentException(" Pass on null  Also want to use   Non empty assertion operators ? It's strange not to make mistakes ")

8、substring

    val info = "You are handsome."    val  indexOf = info.indexOf(".")    println(info.substring(0, indexOf))// kotlin  Basically use the following method to intercept ,  from 0  until (until) indexOf    println(info.substring(0 until indexOf))

9、sqlit operation ( Split operation )

    val  jsonText = " Zhang San , Wang Wu , It's beautiful , Mei Li Yang "// list  Automatic type inference to  list == List<String>    val list = jsonText.split(",")//  Direct output list  aggregate     println(list)// C++  There are deconstruction operations . kotlin  There are also deconstruction operations     val (v1, v2, v3, v4) = list    println(" After deconstruction 4 Data , Namely : v1:$v1, v2: $v2, v3: $v3, v4: $v4")

10、replace Complete the encryption and decoding operation

    val sourcePwd = "qwertyuiopasdfghjklzxcvbnm"    println(sourcePwd)//  Encryption operation : It's the operation of replacing and disrupting characters     val newPwd = sourcePwd.replace(Regex("[asdwq]")){        when(it.value){       //  Poll each character in the string             "a" -> "2"            "s" -> "4"            "d" -> "3"            "w" -> "5"            "q" -> "7"            else -> it.value          // Do nothing , Return the original value directly         }    }    println(newPwd)//  Decryption operation     val sourcePwdNew = newPwd.replace(Regex("[24357]")){        when(it.value){            "2" -> "a"            "4" -> "s"            "3" -> "d"            "5" -> "w"            "7" -> "q"            else -> it.value        }    }    println(sourcePwdNew)

11、== And === Comparison operator

// ==  Is the comparison of content , amount to Java  Medium  equals()// ===  Is the comparison of references , The comparison is the reference in the state pool     val name1 = "Tiger"    val name2 = "tiger"    val name3 = "tiger"    val name4 = name2.capitalize()    println(name1 === name2)    println(name3 == name2)    println(name1 === name4)

12、 Traversal of string

    val str = "qwertyuiopasdfghjklzxcvbnm"    str.forEach {// it  Implicit functions , yes str  Every character in         println(" Traversed data  $it")    }

13、 Safe conversion function of digital type

    val number: Int = "666".toInt()    println(number)    val number1: Int = "666.6".toInt()    //  Put... In the string double  type , convert to int  type , Will fail and cause the program to crash     println(number1)    //  solve   The problem of the crash above     val number2: Int? = "666.6".toIntOrNull()        println(number1 ?: " Character type conversion failed , Return to one null ")

14、Double turn Int Type formatting

//  rounding   The algorithm turns int    println(54.2334.toInt())//  rounding   The algorithm turns int    println(54.2334.roundToInt())//  Keep three decimal places     val r = "%.3f".format(53.3432212)    println(r)

15、apply Built in functions

    val info = "The tiger you are the most handsome"//  Common writing     println("info  The length of the string is  ${info.length}")    println("info  The last character of is  ${info[info.length-1]}")    println("info  Convert all to uppercase characters  ${info.toUpperCase()}")// apply  The way of built-in functions // info.apply  Characteristics :apply  The function always returns  info  In itself  String  type    val str = info.apply {//  In most cases , Anonymous functions , Will hold one it , however apply  Don't hold it, But will hold the current  this == info  In itself        println("info  The length of the string is  ${this.length}")       println("info  The last character of is  ${info[this.length-1]}")       println("info  Convert all to uppercase characters  ${this.toUpperCase()}")//  You can also directly this  Get rid of        println("info  The length of the string is  ${length}")       println("info  The last character of is  ${info[length-1]}")       println("info  Convert all to uppercase characters  ${toUpperCase()}")    }    println(str)//  Really use apply  The method of the function is as follows // info.apply  characteristic : apply  The function always returns  info  In itself , You can use chained calls     info.apply {        println("info  The length of the string is  ${length}")    }.apply {        println("info  The last character of is  ${info[length-1]}")    }.apply {        println("info  Convert all to uppercase characters  ${toUpperCase()}")    }//  File reading small example //  Common writing     val file = File("/Users/tiger/Desktop/aaa.text")    file.setExecutable(true)    file.setReadable(true)    println(file.readLines())// apply  How to write it     val r = file.apply {        setExecutable(true)    }.apply {        setReadable(true)    }.apply {        println(file.readLines())    }

16、let Built in functions

//  The ordinary way , The collection   Add the first data in     val list = listOf(4, 3, 43, 345, 2)    val value1 = list.first()    val result = value1 + value1    println(" The ordinary way   Add the first number of the set and  $result")// let  The way , The collection   Add the first data in     val result2 = list.let {//  Implicit functions  it == list  The assembly itself         it.first() + it.first()    //  The last line of the anonymous function , As return value , Determine return value type     }    println(result2)    println(getMethod("tiger"))    println(getMethod2("tiger"))//  The ordinary way   Value judgment null  And back to fun getMethod(value: String?): String {    return if (value == null) " What you're passing on is null" else " You sent a data over , I'll give it back to you  $value"}// let The way  +  Null merge operator   Value judgment null  And back to fun getMethod2(value: String? ) : String {   return value?.let {        " You sent a data over , I'll give it back to you  $it"    } ?: " You gave one null , And want me to go back ?"}

17、run Built in functions

   val str = "tiger is Ok"    str.run {// run  Anonymous functions and  apply  equally , They all have one  this == str  Ben's function         println(" The input string is : $this")    }    /** *  Use run  Write a small example  * 1、 The named function judges the length of the string , * 2、 The named function judges whether the length is qualified  * 3、 Named functions   Obtain qualified parameters  * 4、 Printout  */    str.run(::isLong)            .run(::showText)            .run(::resultText)            .run(::println)//  Another example of an anonymous function     str.run {        length > 5    }            .run {                if (this) " The string you entered is qualified " else " The string you entered is not qualified "            }            .run {                " I finally got here  $this"            }            .run {                println(this)            }//  Named functions   String length   verification fun isLong(str: String): Boolean {    return str.length > 5}//  Verify that the length is acceptable fun showText(isLong: Boolean): String {    return if (isLong) " The string you entered is qualified " else " The string you entered is not qualified "}//  Get the result after string verification fun resultText(showText: String): String {    return " I finally got here  $showText"}

18、with Built in functions

    val str = "tiger is ok"//  Named functions     val w1 = with(str, ::getLength)    val w2 = with(w1, ::getInfo)    with(w2, ::logInfo)//  Anonymous functions // with  and  apply run  The function is the same , Holding is also this  In itself    with( with(with(str){       length   }){       " The length of the string is 2 $this"   }){       println(this)   }//  Gets the length of the string fun getLength(str: String) = str.length//  Read the value of the above function fun getInfo(len: Int) = " The length of the string is  $len"//  printout fun logInfo(infoMap: String) = println(infoMap)

19、also Built in functions

// also  The return type of , and  apply  equally , Return the type of data , Depending on the type of data passed in // also  Holding is a it,  Here and let  equally     val str = "tiger is ok"    str.also {        println(it.length)    }.also {        println(it.first())    }.also {        println(it.capitalize())    }.also {        println(" It's finally over ")    }

20、takeIf Built in functions

    println(checkPermissionSystem("tiger", "123456"))// takeIf +  Empty security merge fun checkPermissionSystem(name: String, pwd: String): String {    return name.takeIf { permissionSystem(name, pwd) } ?: " Not enough permissions "}//  Authority judgment private fun permissionSystem(userName: String, userPwd: String): Boolean {    return userName == "tiger" && userPwd == "123456"}

21、takeUnless Built in functions

takeIf and takeUnless The function is the opposite
name.takeIf { true/false } true The return is name,false The return is null
name.takeUnless { true/ false } true The return is null ,false Return is name

Why takeUnless Appearance , One takeIf No, it's OK ? Look at the code below

    val manager = Manager();    manager.setInfoValue("tiger")// takeUnless.isNullOrBlank()  Use it together , You can verify whether the string has been initialized     val result = manager.getInfoValue().takeUnless { it.isNullOrBlank() } ?: " Your data is not initialized , Or a null"    println(result)class Manager {    private var infoValue: String? = null    fun getInfoValue() = infoValue    fun setInfoValue(infoValue: String) {        this.infoValue = infoValue    }}

summary

🤩
Originality is not easy. , I also hope you guys can support \textcolor{blue}{ Originality is not easy. , I also hope you guys can support }

give the thumbs-up , Your recognition is the driving force of my creation ! \textcolor{green}{ give the thumbs-up , Your recognition is the driving force of my creation !}

Collection , Your favor is the direction of my efforts ! \textcolor{green}{ Collection , Your favor is the direction of my efforts !}

Comment on , Your opinion is the wealth of my progress ! \textcolor{green}{ Comment on , Your opinion is the wealth of my progress !}

原网站

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