当前位置:网站首页>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
🤩
️
边栏推荐
- Gateway processing flow of zuul source code analysis
- 强化学习之父Richard Sutton论文:追寻智能决策者的通用模型
- 使用 Abp.Zero 搭建第三方登录模块(一):原理篇
- Resolve symbol conflicts for dynamic libraries
- Teach you how to use airtestide to connect your mobile phone wirelessly!
- About the hacked database
- Manuel d'entrevue du gestionnaire de l'analyse des sources
- Implement Domain Driven Design - use ABP framework - update operational entities
- The data value reported by DTU cannot be filled into Tencent cloud database through Tencent cloud rule engine
- Quickly understand the commonly used message summarization algorithms, and no longer have to worry about the thorough inquiry of the interviewer
猜你喜欢
About the hacked database
AGCO AI frontier promotion (6.24)
DTU上报的数据值无法通过腾讯云规则引擎填入腾讯云数据库中
Who is the fish and who is the bait? Summary of honeypot recognition methods from the perspective of red team
面试官:MySQL 数据库查询慢,除了索引问题还可能是什么原因?
Getting started with the go Cobra command line tool
Beauty of script │ VBS introduction interactive practice
Nifi from introduction to practice (nanny level tutorial) - environment
Developer survey: rust/postgresql is the most popular, and PHP salary is low
[data mining] final review (sample questions + a few knowledge points)
随机推荐
Best practices of swagger in egg project
敏捷之道 | 敏捷开发真的过时了么?
发扬连续作战优良作风 全力以赴确保北江大堤安全
Yolov6: the fast and accurate target detection framework is open source
Google Earth Engine——1999-2019年墨累全球潮汐湿地变化 v1 数据集
3. Caller 服务调用 - dapr
How can the new webmaster avoid the ups and downs caused by SEO optimization?
Vipshop's "special sale" business is no longer easy to do?
这几个默认路由、静态路由的配置部署都不会,还算什么网工!
Main steps of system test
Can inspection results be entered after the completion of inspection lot UD with long-term inspection characteristics in SAP QM?
#yyds干货盘点# 解决剑指offer:调整数组顺序使奇数位于偶数前面(二)
Comparator 排序函数式接口
Gateway processing flow of zuul source code analysis
10 reduce common "tricks"
Detailed explanation of kotlin collaboration lanch
首席信息安全官仍然会犯的漏洞管理错误
Internet of things? Come and see Arduino on the cloud
Source code analysis handler interview classic
硬件开发笔记(六): 硬件开发基本流程,制作一个USB转RS232的模块(五):创建USB封装库并关联原理图元器件