当前位置:网站首页>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
边栏推荐
- [competition -kab micro entrepreneurship competition] KAB National College Students' micro entrepreneurship action participation experience sharing (including the idea of writing the application form)
- Is it safe to open an account online? Who can I ask?
- [MySQL learning notes 20] MySQL architecture
- CYCA 2022少儿形体礼仪初级师资班 深圳总部站圆满结束
- Wallys/MULTI-FUNCTION IPQ6010 (IPQ6018 FAMILY) EMBEDDED BOARD WITH ON-BOARD WIFI DUAL BAND DUAL
- puzzle(019.2)六边锁
- Remittance international empowers cross-border e-commerce: to be a compliant cross-border payment platform!
- js工具函数,自己封装一个节流函数
- How to make a self-made installer and package the program to generate an installer
- (forwarding articles) after skipping multiple pages, shuttle returns to the first page and passes parameters
猜你喜欢

Summarize two methods of configuring pytorch GPU environment

Ruiji takeout project (II)

2台三菱PLC走BCNetTCP协议,能否实现网口无线通讯?
![[wechat applet full stack development course] course directory (mpvue+koa2+mysql)](/img/1c/ab39cf0a69d90a85665a099f5dbd26.jpg)
[wechat applet full stack development course] course directory (mpvue+koa2+mysql)

x86的编码格式

Chitubox micromake l3+ slicing software configuration correspondence

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

Remove the mosaic, there's a way, attached with the running tutorial

2021mathorcupc topic optimal design of heat dissipation for submarine data center

How to download the school logo, school name and corporate logo on a transparent background without matting
随机推荐
MySQL source code reading (II) login connection debugging
[buuctf.reverse] 121-125
Learning notes of rxjs takeuntil operator
Wearable devices may reveal personal privacy
Neat Syntax Design of an ETL Language (Part 2)
Get started quickly with jetpack compose Technology
Pytorch_ Geometric (pyg) uses dataloader to report an error runtimeerror: sizes of tenants must match except in dimension 0
[2020 cloud development + source code] 30 minutes to create and launch wechat applet practical project | zero cost | cloud database | cloud function
【mysql学习笔记22】索引
Is it safe to open an account on the compass?
Online notes on Mathematics for postgraduate entrance examination (8): Kego equations, eigenvalues and eigenvectors, similarity matrix, quadratic series courses
STM32 receives data by using idle interrupt of serial port
CyCa children's physical etiquette Yueqing City training results assessment successfully concluded
[project part - structure and content writing of technical scheme] software system type mass entrepreneurship and innovation project plan and Xinmiao guochuang (Dachuang) application
Jetpack compose layout (II) - material components and layout
How do dating applets make millions a year? What is the profit model?
[Ruby on rails full stack course] course directory
[buuctf.reverse] 121-125
x86电脑上下载debian的arm64的包
51 SCM time stamp correlation function