当前位置:网站首页>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
边栏推荐
- [buuctf.reverse] 121-125
- Is GF Securities reliable? Is it legal? Is it safe to open a stock account?
- Pytorch_Geometric(PyG)使用DataLoader报错RuntimeError: Sizes of tensors must match except in dimension 0.
- With the QQ group file storage function of super nice, you immediately have n cloud disks that are easy to download and never expire
- Set the location permission in the shutter to "always allow"
- Tiktok brand goes to sea: both exposure and transformation are required. What are the skills of information flow advertising?
- 【mysql学习笔记22】索引
- Is it safe to open an account with Great Wall Securities by mobile phone?
- 2022 meisai question a idea sharing
- Get started quickly with jetpack compose Technology
猜你喜欢
[buuctf.reverse] 117-120
Notes on writing questions in C language -- monkeys eat peaches
Nano data World Cup data interface, CSL data, sports data score, world cup schedule API, real-time data interface of football match
Remove the mosaic, there's a way, attached with the running tutorial
瑞萨RA系列-开发环境搭建
Can two Mitsubishi PLC adopt bcnettcp protocol to realize wireless communication of network interface?
Remittance international empowers cross-border e-commerce: to be a compliant cross-border payment platform!
[wechat applet full stack development course] course directory (mpvue+koa2+mysql)
Cassava tree disease recognition based on vgg16 image classification
[MySQL learning notes 22] index
随机推荐
Applet cloud development joint table data query and application in cloud function
puzzle(019.2)六边锁
‘Flutter/Flutter. h‘ file not found
Online notes on Mathematics for postgraduate entrance examination (8): Kego equations, eigenvalues and eigenvectors, similarity matrix, quadratic series courses
Question B of the East China Cup: how to establish a population immune barrier against novel coronavirus?
Learning notes of rxjs takeuntil operator
Nano data World Cup data interface, CSL data, sports data score, world cup schedule API, real-time data interface of football match
How to make a self-made installer and package the program to generate an installer
Get started quickly with jetpack compose Technology
Flutter replaces the default icon of Gaud positioning
oracle 函数 触发器
[shared farm] smart agriculture applet, customized development and secondary development of Kaiyuan source code, which is more appropriate?
Fluent creates, reads and writes JSON files
manhattan_slam环境配置
Jetpack compose layout (I) - basic knowledge of layout
Cubemx stm32f105rb USB flash drive reading and writing detailed tutorial
[buuctf.reverse] 117-120
Where is safe for FTSE A50 to open an account
[zero foundation understanding innovation and entrepreneurship competition] overall cognition and introduction of mass entrepreneurship and innovation competition (including FAQs and integration of bl
[buuctf.reverse] 121-125