当前位置:网站首页>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 b
1.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): String
1、 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 = "" ): String
3、 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 = 5
1.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
边栏推荐
- 15. Notes on the button style of WPF
- VFP function to summarize all numeric columns of grid to cursor
- 机器学习自学成才的十条戒律
- VFP serial port communication is difficult for 9527. Maomao just showed his skill and was defeated by kiss
- VFP develops a official account to receive coupons, and users will jump to various target pages after registration, and a set of standard processes will be sent to you
- SDN系统方法 | 9. 接入网
- 黑马畅购商城---3.商品管理
- Web project development process
- R语言dplyr包summarise_at函数计算dataframe数据中多个数据列(通过向量指定)的计数个数、均值和中位数、在每个函数内部指定na.rm参数、通过list指定函数列表
- ARM V7 连续加载/存储
猜你喜欢
SQL server saves binary fields to disk file
A set of automated paperless office system (oa+ approval process) source code: with data dictionary
Old ou, a fox friend, has had a headache all day. The VFP format is always wrong when it is converted to JSON format. It is actually caused by disordered code
The cloud native data lake has passed the evaluation and certification of the ICT Institute with its storage, computing, data management and other capabilities
Thingpanel publie le client mobile IOT (Multi - images)
Time series analysis - how to use unit root test (ADF) correctly?
Caused by: org. xml. sax. SAXParseException; lineNumber: 1; columnNumber: 10; Processing matching '[xx][mm][ll]' is not allowed
揭秘GaussDB(for Redis):全面對比Codis
plt.gca()画框及打标签
Rank sum ratio comprehensive evaluation method for common models in mathematical modeling
随机推荐
How to use SPSS to do grey correlation analysis? Quick grasp of hand-to-hand Teaching
ArcGIS services query filter by time field
Gradle知识点
做自媒体视频需要怎么做才能年收入一百万?
R语言dist函数计算dataframe数据中两两样本之间的距离返回样本间距离矩阵,通过method参数指定距离计算的方法、例如欧几里得距离
Thirty lines of code prevent VFP forms from running repeatedly, and the function supports parameter transfer
Pd1.4 to hdmi2.0 adapter cable disassembly.
Web project development process
Why should Apple change objc_ Type declaration for msgsend
Continue to cut the picture after the ArcGIS Server is disconnected
How terrible is it not to use error handling in VFP?
cnds
[论]Learning Dynamic and Hierarchical Traffic Spatiotemporal Features with Transformer
Effective reading of literature
黑馬暢購商城---3.商品管理
客户经理的开户二维码开户买股票安全吗?有谁知道啊
An easy-to-use seal design tool - (can be converted to ofd file)
黑马畅购商城---6.品牌、规格统计、条件筛选、分页排序、高亮显示
刷入Magisk通用方法
黑马畅购商城---8.微服务网关Gateway和Jwt令牌