当前位置:网站首页>Kotlin study notes
Kotlin study notes
2022-06-25 12:15:00 【User 9854323】
List of articles - One . Kotlin Basic knowledge of
One . Kotlin Basic knowledge of
1.1 Function structure :
Block volume :
fun max(a: Int, b: Int): Int {
return if (a > b) a else b
}The above formula can be written as the following expression body (Kotlin You will know the type of the expression through type derivation ):
fun max(a:Int, b:Int) = if (a > b) a else b1.2 Variable
Kotlin The syntax for defining variables is : var/val name:Type
- var (variable ), You can modify
- val ( value ), Do not modify
var age : Int = 17 // Define a variable that can be modified
val ID : String= "1000" // Define an immutable variable
// You can also omit variable types ,Kotlin Can deduce the type of variable
var age = 17
val id = "1000"Be careful :val Represents the variable Reference immutable , But the content in the object can change
1.3 when、 Loop statement
1.3.1 when
stay Java There is switch sentence , stay Kotlin Use in when Instead of switch
when( Parameters ){
Parameters 1 -> {
//...
}
Parameters 1 -> {
//...
}}1.3.2 Loop statement
Kotlin Medium while and do…while Circulation and Java There is no difference between :
while (condition) {
//
}
do {
//
} while (condition)for Circulation and Java The difference is :
// Java for loop
for (int i = 0; i <= 100; i++) {
System.out.println(i);
}
// Corresponding Kotlin edition
for(i in 0..100){
println(i)
}1)、 Closed interval : Use … The operator Represents an interval , The interval is closed , Elements that contain the start and end , And then use in Operator to traverse the interval 2)、 Semi closed interval : That is, only the header element is included , Not including the tail :until
for(i in 0 until 100){
println(i)
}3)、 Reverse traversal :downTo( Closed interval )
for(i in 100 downTo 0){
println(i)
}4)、 step : When traversing step (step) The default is 1, Can pass step Keyword to specify the step size
for( i in 100 downTo 0 step 2){
println(i)
}1.4 Kotlin exception handling
1)、throw The key word in Kotlin Medium is expression , There is a return value
val percentage = if (number in 0..100)
number
else
throw IllegalArgumentException(
"A percentage value must be between 0 and 100: $number")2)、Kotlin You don't have to throw an exception up in (java Must throw , Otherwise, it can't be compiled )
fun readNumber(reader: BufferedReader): Int?{
try {
val line = reader.readLine() // throws IOException
return Integer.parseInt(line) // throws NumberFormatException
} catch (e: NumberFormatException) {
return null
} finally {
reader.close() // throws IOException
}
}java Middle principle :
int readNumber( BufferedReader reader) throws IOException {
try {
String line = reader.readLine(); // throws IOException
return Integer.parseInt(line); // throws NumberFormatException
} catch (NumberFormatException e) {
return -1;
} finally {
reader.close(); // throws IOException
}
}1.5 “?” and “!!”
1. When you declare an object ( Include method parameters ):
- hold "?" After the class name , Indicates that this object is allowed to be null;
- hold "!!" After the class name , Indicates that this object is not allowed to be null; 2. When calling an object :
- hold "?" Follow the object , If it means null, The program will turn a blind eye , No null pointer .
- hold "!!" Follow the object , If it means null, Then the system will report an exception .
// This is to declare a variable , The question mark follows the class name
var room: Room? = Room()
private fun checkRoom() {
// Because of the question mark , So you can put room Become empty
room = null
// Because you put a question mark on the call , So the program will not throw an exception
Log.d("TAG", "-->> room name = ${room?.roomName}")
}Method parameters are also similar to declaring a variable
fun test(){
heat(null) // Compile
heat1(null) // Compile but
}
// Parameters str It can be transmitted null
fun heat(str: String?): String{
return str + " heat "
}
// Parameters str You can't pass null
fun heat1(str: String): String{
return str + " heat "
}var str: String? = "ds";
var length = str?.length;
var str2: String? = null
var length2 = str2?.length;
var str1: String = "ds";
var length1 = str1!!.length;
var str3: String? = null
var length3 = str3!!.length;
// After compiling
String str = "ds";
int length = str.length();
String str2 = (String)null;
Integer length2 = null;
String str1 = "ds";
int length1 = str1.length();
String str3 = (String)null;
Intrinsics.throwNpe();
int length3 = str3.length();- If not "?"
// In this way, the program will default to room Combined with the !!, From then on room It is not allowed to be null
var room: Room = Room()
private fun checkRoom() {
// When put null Assign to room when , Compilation will not pass
room = null
// And the compiler recommends deleting the question mark after the object , Because this object is never empty
Log.d("TAG", "-->> room name = ${room.roomName}")
}- When defining variables "?" Use
val room: Room? = Room() // Instantiate a room, also room Can be null
val room: Room? = null // No more , Start room It's empty.
val room: Room = Room() // Instantiate a room, also room Can never be empty
val room = Room() // As in the previous line of code , It's abbreviated grammar - Used “?” It really won't NullPointerException Why? ?
val roomList: ArrayList<Room>? = null
if (roomList?.size > 0) {
Log.d("TAG", "-->> Number of rooms is not 0")
}The compiler will tell us : When roomList by null When the , its size Return is "null", however "null" Not with int Value ratio size , So the compiler suggests that we write roomList?.size!! > 0, But this will definitely report NullPointerException.
Do you have to put a layer on the outside if(roomList != null) such Java Can common statements avoid exceptions ? however Kotlin Will not let the program appear this kind of verbose code , So it provides objects A ?: object B expression , ?: It means , Be the object A The value is null When , Then it will return the following objects B, So it can be written as :
val roomList: ArrayList<Room>? = null
if (roomList?.size ?: 0 > 0) { // This line adds ?:
Log.d("TAG", "-->> Number of rooms is not 0")
}So far make , With the above ? and ?: Basically, it can avoid all the problems in the program NullPointerException.
- If the variable can be null( Using operators "?"), Then it is the wrapper type after compilation
// Because it can help null, So it is compiled as Integer
var width: Int? = 10
var width: Int? = null
// Compiled code
@Nullable
private static Integer width = 10;
@Nullable
private static Integer width;
// Let's see that the return value of the method is integer :
// Return value Int After compilation, it becomes a basic type int
fun getAge(): Int {
return 0
}
// Return value Int Compiled to Integer
fun getAge(): Int? {
return 0
}1.6 Overloaded calling function
Suppose we have the following function :
fun <T> joinToString(collection: Collection<T>,
separator: String,
prefix: String,
postfix: String): String1、 call ( Specify the parameter name for the parameter value ):
joinToString(collection, separator = " ", prefix = " ", postfix = ".")2、 Specify default values for function parameters :
fun <T> joinToString(collection: Collection<T>,
separator: String = ", ",
prefix: String = "",
postfix: String = "" ): String3、 Overload calls ( Only when there is a default value )
joinToString(list)
joinToString(list, prefix = "# ")1.7 Top level functions and properties ( Static )
stay Java We need to put functions and attributes in a class , stay Kotlin We can put a function or attribute directly into a Kotlin In file , Call such a function or attribute Top level functions or properties .
For example, in join.kt In file :
package strings
fun joinToString(...): String {
...
}1)、 But in Java How to call this method in the code ? because JVM Virtual machines can only execute code in classes , therefore Kotlin Will generate a file named JoinKt Class , And top-level functions are static , So it can be Java Call the top-level function in this way :
JoinKt.joinToString(...)2)、 stay Kotlin How to call , If in different packages , You need to import this top-level function to call :
// amount to import strings.JoinKt.joinToString
import strings.joinToString
// amount to import strings.JoinKt.*
import strings.* 3)、 Top attributes also static Static If you use var To define that the corresponding static setter、getter function If you use val To define that only the corresponding static getter function
4)、Kotlin What if the file name is modified ? If you are in Kotlin The file name has been modified , The compiled class name will also be modified , The class name generated by compilation can be fixed through annotation :
@file:JvmName("StringFunctions")
package stringsfun joinToString(...): String {
...
} When called :import strings.StringFunctions;
StringFunctions.joinToString(list, ", ", "", "");1.8 Variable parameters and Expansion operator
1)、 Variable parameters , Any number of parameters can be passed java Use in … To declare variable parameters , Such as :
public static <T> List<T> listOf(T... items) {
System.out.println(items.getClass()); // An array type
return Arrays.asList(items);
}Kotlin and Java Dissimilarity ,Kotlin Use vararg Key to define variable parameters :
fun <T> listOf(vararg items: T): List<T> {
println(items.javaClass) // An array type
return Arrays.asList(*items) // * spread operator
}2)、 Expansion operator By comparing the above two pieces of code, we find that :Kotlin The variable parameters that need to be displayed are passed through * an , And pass it to asList function . there * Namely Expansion operator , stay Java There is no Expansion operator Of .
- When the expansion operator is not used :
val intArr: Array<Int> = arrayOf(1, 2, 3, 4)
Arrays.asList(0, intArr).run {
println("size = $size")}
// Output results :
size = 2- When using the expand operator :
val intArr: Array<Int> = arrayOf(1, 2, 3, 4)
Arrays.asList(0, *intArr).run {
println("size = $size")}
// Output results :
size = 51.9 Infix call infix
Use keywords infix Decorated functions can Infix call , By keyword infix Decorated functions can only have one parameter .
Kotlin Medium to Is a infix function :
public infix fun <A, B> A.to(that: B): Pair<A, B> = Pair(this, that)Let's compare to Regular and infix calls to functions :
1.to("one") // Ordinary function call
1 to "one" // Infix call of function except to function , And we introduce loop I talked about it when I was young until、downTo、step It's also an infix function :
public infix fun Int.until(to: Int): IntRange {
if (to <= Int.MIN_VALUE) return IntRange.EMPTY
return this .. (to - 1).toInt()
}
public infix fun Int.downTo(to: Int): IntProgression {
return IntProgression.fromClosedRange(this, to, -1)
}
public infix fun IntProgression.step(step: Int): IntProgression {
checkStepIsPositive(step > 0, step)
return IntProgression.fromClosedRange(first, last, if (this.step > 0) step else -step)
}
// Examples of use :
for(i in 0 until 100){}
for (i in 100 downTo 0 step 2) {}1.10 Local function
Local function (local function) Is to define a function in a function , Local functions can only be used inside functions When to use local functions ? When the logic in a function is a lot of repetitive logic , You can extract this logic into a local function .
fun saveUser(user: User) {
if (user.name.isEmpty()) {
throw IllegalArgumentException("Cannot save user ${user.id}: Name is empty")
}
if (user.address.isEmpty()) {
throw IllegalArgumentException("Cannot save user ${user.id}: Address is empty")
}
}This saveUser There is some repeating logic in the function , If name or address If it is empty, an exception will be thrown You can use local functions to optimize :
fun saveUser(user: User) {
fun validate(value: String, fieldName: String) {
if (value.isEmpty()) {
throw IllegalArgumentException("Can't save user ${user.id}: " + "$fieldName is empty")
}
}
validate(user.name, "Name")
validate(user.address, "Address")
}Native functions avoid template code . If you do not use local functions , We need to take validate function Define to the outside , But this function will only be saveUser function Use to , Thus polluting the external global scope . Make the code clearer through local functions , More readable . Be careful : although Kotlin Allows you to define functions inside functions , But don't nest too deeply , Otherwise, it will lead to poor readability
1.11 Access modifier
- Class access modifiers are as follows :
- Class member access modifier :
- Only ‘’protected‘’ Corresponding ‘’Kotlin Access level ‘’ There's a difference : Only subclasses can access
1.12 Several ways to declare classes
- class className : This class is public final Of
class Person
After compiling :
public final class Person {
}- class className([var/val] property : Type…)
- 1、 Will generate a constructor , Parameters are those in parentheses
- 2、 The corresponding properties will be generated according to the parameters in parentheses
- 3、 Will be based on val and var Keyword to generate setter、getter Method ,var Indicates that the attribute can be modified ;val Indicates that the property cannot be modified
class Person(val name: String) //name Property cannot be modified
--- After compiling ---
public final class Person {
//1. Generate name attribute
@NotNull
private final String name;
//2. Generate getter Method
// because name Property cannot be modified , So we don't offer name Of setter Method
@NotNull
public final String getName() {
return this.name;
}
//3. Build constructor
public Person(@NotNull String name) {
Intrinsics.checkParameterIsNotNull(name, "name");
super();
this.name = name;
}
}- data class className([var/val] property: Type)
- newly build bean Class time , It is often necessary to declare equals、hashCode、toString Other methods , We need to write a lot of code .
- stay Kotlin in , Just add... Before declaring the class data Keywords can complete these functions .
- Be careful : Which attributes participate in equals、hashCode、toString Methods? ?primary constructor Arguments in the constructor , Will participate in equals、hashCode、toString In the method .
- object className The class declared by this method is a singleton class , before Java Create a new singleton class in , Need to write some template code , stay Kotlin Just one line of code in ( Before the class name, add object keyword ).
- Inner class
- stay Kotlin The inner class in is static by default ( Java On the contrary ), Does not hold references to external classes :
class OuterClass {
// stay Kotlin The inner class in is static by default , Does not hold references to external classes
class InnerStaticClass{
}
// If you want to declare a non static inner class , Need to add inner keyword
inner class InnerClass{
}
}
The compiled code is as follows :
class OuterClass {
public static final class InnerStaticClass {
}
public final class InnerClass {
}
}1.13 Static variables and static methods
边栏推荐
- 网络 | traceroute,路由跟踪命令,用于确定 IP 数据包访问目标地址所经过的路径。
- Is it safe to open an account and buy stocks? Who knows
- JS to realize the calculation of discrete aggregation points
- What are redis avalanche, penetration and breakdown?
- Mpai data science platform random forest classification \ explanation of regression parameter adjustment
- A set of automated paperless office system (oa+ approval process) source code: with data dictionary
- Update of complex JSON in MySQL
- JS monitors the width and height changes of div
- 数据库系列:MySQL索引优化总结(综合版)
- 黑马畅购商城---1.项目介绍-环境搭建
猜你喜欢

What should I do to dynamically add a column and button to the gird of VFP?

黑马畅购商城---6.品牌、规格统计、条件筛选、分页排序、高亮显示

confluence7.4. X upgrade record

黑马畅购商城---2.分布式文件存储FastDFS

Windows11 MySQL service is missing

Pd1.4 to hdmi2.0 adapter cable disassembly.

Thingspanel releases Internet of things mobile client (multiple pictures)

优品购电商3.0微服务商城项目实战小结

SQL server saves binary fields to disk file

How far is it from the DBF of VFP to the web salary query system?
随机推荐
Why can't you Ping the website but you can access it?
架构师为你揭秘在阿里、腾讯、美团工作的区别
做自媒体视频需要怎么做才能年收入一百万?
Redis雪崩、穿透和击穿是什么?
Architects reveal the difference between working in Alibaba, Tencent and meituan
数据库系列:MySQL索引优化总结(综合版)
Develop two modes of BS mode verification code with VFP to make your website more secure
Use of JSP sessionscope domain
Le détour d'un ingénieur en matériel
ARM 立即数
JS to realize the calculation of discrete aggregation points
ARM V7 ldr str 内存访问
How to open an account for trading futures Shanghai nickel products online
How can we make an annual income of onemillion yuan by making our own media video?
ARM V7 连续加载/存储
If you also want to be we media, you might as well listen to Da Zhou's advice
一個硬件工程師走過的彎路
黑馬暢購商城---3.商品管理
Thingpanel publie le client mobile IOT (Multi - images)
网络上开户买股票是否安全呢?