当前位置:网站首页>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
边栏推荐
- 2022 postgraduate entrance examination experience post -- Alibaba Business School of Hangzhou Normal University -- management science and Engineering (including the recommendation of books and course
- [design completion - opening report] zufeinfo 2018 software engineering major (including FAQ)
- What are the PMP scores?
- Register the jar package as a service to realize automatic startup after startup
- Mengyou Technology: six elements of tiktok's home page decoration, how to break ten thousand dollars in three days
- Is it safe to open a stock account through the account opening QR code of the account manager?
- manhattan_ Slam environment configuration
- clang frontend command failed with exit code 250
- Title B of the certification cup of the pistar cluster in the Ibagu catalog
- An auxiliary MVP architecture project quick development library -mvpfastdagger
猜你喜欢
![[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

Register the jar package as a service to realize automatic startup after startup

Rxjs TakeUntil 操作符的学习笔记

瑞吉外卖项目(二)

Jetpack compose layout (II) - material components and layout
![[buuctf.reverse] 117-120](/img/6c/8a90fff2bd46f1494a9bd9c77eeafc.png)
[buuctf.reverse] 117-120

vscode试图过程写入管道不存在

Compare and explain common i/o models

I put a two-dimensional code with rainbow candy
![[learn C from me and master the key to programming] insertion sort of eight sorts](/img/2c/22e065390464ed5cd1056346d46573.jpg)
[learn C from me and master the key to programming] insertion sort of eight sorts
随机推荐
PHP obtains the IP address, and the apache2 server runs without error
Cubemx stm32f105rb USB flash drive reading and writing detailed tutorial
CyCa 2022 children's physical etiquette primary teacher class Shenzhen headquarters station successfully concluded
Huipay international permet au commerce électronique transfrontalier de devenir une plate - forme de paiement transfrontalière conforme!
JS tool function, self encapsulating a throttling function
Is it safe to open an account on the compass?
Can two Mitsubishi PLC adopt bcnettcp protocol to realize wireless communication of network interface?
C语言刷题随记 —— 猴子吃桃
Wechat official account can reply messages normally, but it still prompts that the service provided by the official account has failed. Please try again later
Data-driven anomaly detection and early warning of 21 May Day C
Simple waterfall effect
Solution to the problem of repeated startup of esp8266
The problem of automatic page refresh after the flyer WebView pops up the soft keyboard
Force buckle -104 Maximum depth of binary tree
How to "transform" small and micro businesses (II)?
Vscode attempted to write the procedure to a pipeline that does not exist
x86电脑上下载debian的arm64的包
Is it harder to find a job in 2020? Do a good job in these four aspects and find a good job with high salary
With the QQ group file storage function of super nice, you immediately have n cloud disks that are easy to download and never expire
富时A50开户什么地方安全