当前位置:网站首页>Kotlin introductory notes (III) kotlin program logic control (if, when)
Kotlin introductory notes (III) kotlin program logic control (if, when)
2022-07-05 09:14:00 【Meng Meng Mu Xi】
Preface : This tutorial is best done with JAVA Study on the basis of
One 、if Use of statements
kotlin There are two main ways to implement conditional statements in :if and when.
Same usage :
fun largerNumber(num1 : Int , num2 : Int) : Int{
var value = 0
if(num1 > num2) {
value = num1
} else {
value = num2
}
return value
}Different usage :
fun largerNumber(num1 : Int , num2 : Int) : Int {
val value = if (num1 > num2){
num1
}else{
num2
}
return value
}kotlin And java Of if The statements are roughly the same , but kotlin Of if Statement can have a return value !!!
But there is a problem with the above code ,kotlin It is the most concise language , The above code has too many unnecessary parts . stay kotlin in , We can use the following expression instead ( If you have unclear friends, you can read my first two blogs ):
fun largerNumber(num1 : Int,num2 : Int) = if(num1 > num2) num1 else num2Does it look much more comfortable ? Hem ...,Kotlin The charm of is still behind !
Two 、When sentence
use when And those still in use switch...case Compared with the language of , It's so happy ...( Roast about what anti human can't get rid of break) Don't talk much , Here comes the example ...... Ah , This example is complete , Why don't you see it yet ....
Suppose you compile a function to query exam scores ( if sentence ):
fun getScore(name : String) = if (name == "Tom") {
86
} else if (name == "Jim") {
77
} else if (name == "Jack") {
95
} else if (name == "Lily") {
100
} else {
0
}But when we use when when , You can compare :
fun getScore(name : String) = when (name) {
"Tom" -> 86
"Jim" -> 77
"Jack" -> 95
"Lily" -> 100
else -> 0
}Is it refreshing ?
The format is as follows :
when( Any type of parameter ) {
Match the value -> { Perform logical }
}
When the execution logic has only one sentence , { } It can also be omitted . Of course , It's an exact match . In addition to precise matching , We also have type matching ... Examples are as follows :
fun checkNumber(num : Number) {
when (num) {
is Int -> println("num is Int")
is Double -> println("num is Double")
else -> println("num neither Int, Neither Double")
}
}when There is another way to write a statement without parameters
Take the example just now :
fun getScore(name : String) = when {
name == "Tom" -> 86
name == "Jim" -> 77
name == "Jack" -> 95
name == "Jack" -> 100
else -> 0
}Be careful ,Kotlin When judging whether strings or objects are equal, you can directly use == .( And Java Different )
In addition to this precise match ,when It can also cooperate with startsWith() Realization Fuzzy matching ( With Tom Everyone at the beginning 86 branch ):
fun getScore(name : String) = when {
// With Tom Everyone at the beginning 86 branch
name.startsWith("Tom") -> 86
name == "Jim" -> 77
name == "Jack" -> 95
name == "Jack" -> 100
}Okay , That's all for this issue , Remember to pay attention if you like !!! RI Geng Zhong !!!
Kotlin The small white , I took notes while studying teacher Guolin's works . If there are any mistakes, please point out ! Thank you for reading !
Reference resources :
《 First line of code Android ( The third edition )》 --- Guo Lin
边栏推荐
- 牛顿迭代法(解非线性方程)
- Uni app implements global variables
- Beautiful soup parsing and extracting data
- Blogger article navigation (classified, real-time update, permanent top)
- Generate confrontation network
- Solutions of ordinary differential equations (2) examples
- 基于STM32单片机的测温仪(带人脸检测)
- Multiple solutions to one problem, asp Net core application startup initialization n schemes [Part 1]
- 2311. 小于等于 K 的最长二进制子序列
- Introduction Guide to stereo vision (1): coordinate system and camera parameters
猜你喜欢

Nodejs modularization

L'information et l'entropie, tout ce que vous voulez savoir est ici.
![Multiple solutions to one problem, asp Net core application startup initialization n schemes [Part 1]](/img/c4/27ae0d259abc4e61286c1f4d90c06a.png)
Multiple solutions to one problem, asp Net core application startup initialization n schemes [Part 1]

高性能Spark_transformation性能

Solution to the problems of the 17th Zhejiang University City College Program Design Competition (synchronized competition)

Nodemon installation and use

Wechat H5 official account to get openid climbing account

Understanding rotation matrix R from the perspective of base transformation

2020 "Lenovo Cup" National College programming online Invitational Competition and the third Shanghai University of technology programming competition

【ManageEngine】如何利用好OpManager的报表功能
随机推荐
2310. 个位数字为 K 的整数之和
Shutter uses overlay to realize global pop-up
Rebuild my 3D world [open source] [serialization-3] [comparison between colmap and openmvg]
Causes and appropriate analysis of possible errors in seq2seq code of "hands on learning in depth"
[beauty of algebra] singular value decomposition (SVD) and its application to linear least squares solution ax=b
kubeadm系列-01-preflight究竟有多少check
Wechat H5 official account to get openid climbing account
太不好用了,长文章加图文,今后只写小短文
ROS learning 4 custom message
[technical school] spatial accuracy of binocular stereo vision system: accurate quantitative analysis
My experience from technology to product manager
Node collaboration and publishing
迁移学习和域自适应
Codeforces Round #648 (Div. 2) E.Maximum Subsequence Value
What is a firewall? Explanation of basic knowledge of firewall
Transfer learning and domain adaptation
Introduction Guide to stereo vision (5): dual camera calibration [no more collection, I charge ~]
一题多解,ASP.NET Core应用启动初始化的N种方案[上篇]
深入浅出PyTorch中的nn.CrossEntropyLoss
STM32简易多级菜单(数组查表法)