当前位置:网站首页>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
边栏推荐
- Wearable devices may reveal personal privacy
- 51 SCM time stamp correlation function
- Remittance international empowers cross-border e-commerce: to be a compliant cross-border payment platform!
- 2021mathorcupc topic optimal design of heat dissipation for submarine data center
- STM32 receives data by using idle interrupt of serial port
- Exception: gradle task assemblydebug failed with exit code 1
- Mengyou Technology: tiktok live broadcast with goods elements hot topics retention skills shaping image highlight selling points
- Use Navicat to compare data differences and structure differences of multi environment databases, and automatic DML and DDL scripts
- MySQL创建给出语句
- The gradle configuration supports the upgrade of 64 bit architecture of Xiaomi, oppo, vivo and other app stores
猜你喜欢

Learning notes of rxjs takeuntil operator

【mysql学习笔记21】存储引擎

Etcd教程 — 第四章 Etcd集群安全配置

Question B of the East China Cup: how to establish a population immune barrier against novel coronavirus?

可穿戴设备或将会泄露个人隐私

Why should the terminal retail industry choose the member management system

Data-driven anomaly detection and early warning of 21 May Day C
![[zufe expense reimbursement] zhecai invoice reimbursement specification (taking Xinmiao reimbursement as an example), which can be passed in one trip at most](/img/28/c5c6b6d03b459745dc3735f8b39ea9.jpg)
[zufe expense reimbursement] zhecai invoice reimbursement specification (taking Xinmiao reimbursement as an example), which can be passed in one trip at most

Exception: gradle task assemblydebug failed with exit code 1

Rxjs TakeUntil 操作符的学习笔记
随机推荐
Wallys/MULTI-FUNCTION IPQ6010 (IPQ6018 FAMILY) EMBEDDED BOARD WITH ON-BOARD WIFI DUAL BAND DUAL
如何自制一个安装程序,将程序打包生成安装程序的办法
MySQL create given statement
Get started quickly with jetpack compose Technology
Mengyou Technology: six elements of tiktok's home page decoration, how to break ten thousand dollars in three days
Pytorch_ Geometric (pyg) uses dataloader to report an error runtimeerror: sizes of tenants must match except in dimension 0
MySQL创建给出语句
Is it safe to open a stock account on the compass?
可穿戴设备或将会泄露个人隐私
Title B of the certification cup of the pistar cluster in the Ibagu catalog
Fcpx quickly add subtitles | Final Cut Pro import fcpxml subtitle file does not match the video time? I got it in code
Learning notes of rxjs takeuntil operator
Is it safe to open a stock account through the account opening QR code of the account manager?
[matlab] image binarization (imbinarize function)
Unique Wulin, architecture selection manual (including PDF)
Can two Mitsubishi PLC adopt bcnettcp protocol to realize wireless communication of network interface?
匯付國際為跨境電商賦能:做合規的跨境支付平臺!
[buuctf.reverse] 121-125
Fluent: target support file /pods runner / pods runner frameworks Sh: permission denied - stack overflow
Grabcut image segmentation in opencv