当前位置:网站首页>Kotlin quick start
Kotlin quick start
2022-06-26 03:19:00 【Azadoo】
val + Variable name :final Type object
var + Variable name : Common object
Declare and initialize :val + Variable name = class ()
val mLintPaint = Paint()
When defining variables , You can add a question mark after the type ?, Indicates that the variable is Nullable, Not adding means that the variable cannot be null. as follows :
var s:String? = null
var s2:String = “xxx” // If the variable is assigned to null, The compilation fails
Declaration array :
var long_array:LongArray = longArrayOf(1, 2, 3)
var float_array:FloatArray = floatArrayOf(1.0f, 2.0f, 3.0f)
var double_array:DoubleArray = doubleArrayOf(1.0, 2.0, 3.0)
var boolean_array:BooleanArray = booleanArrayOf(true, false, true)
var char_array:CharArray = charArrayOf(‘a’, ‘b’, ‘c’)
var string_array:Array = arrayOf(“How”, “Are”, “You”)
val list4 = arrayListOf(“ human beings ”, “ High-quality ”, “ Code the agriculture ”)
lateinit keyword :
- lateinit var Can only be used to decorate class properties , It can't be used to modify local variables , And can only be used to decorate objects , Cannot be used to decorate basic types ( Because the properties of the basic type will be initialized to the default value in the preparation stage after the class is loaded ).
- lateinit var The function of is also relatively simple , This is to prevent the compile time from reporting errors because the attribute variables are not initialized .
- Kotlin Believe that when developers explicitly use lateinit var Keyword time , He will also initialize the attribute object at a reasonable time later
Example : Declare an object that is not instantiated
lateinit var name: String
Method
routine :fun + Method name (){}
Method with return value :
fun methodName(param1: Int, param2: Int): Int {
return 0
}
Inherit
Again kotlin in Classes are not allowed to be inherited by default If you want to set it as a class that can be inherited need open keyword
Such as :open class Person { ... }
Like inheritance View Use it directly : Instead of extends At the same time, the constructor is directly declared
class ClassName(context: Context?) : View(context) {}
Any object-oriented programming language will have the concept of constructor ,Kotlin There are also , however Kotlin There are two kinds of constructors : Primary and secondary constructors .
The main constructor will be your most commonly used constructor , By default, each class has a primary constructor without parameters , Of course, you can also explicitly specify parameters for it . The feature of the primary constructor is that there is no function body , It can be defined directly after the class name . For example, the following way of writing :
class Student(val sno: String, val grade: Int) : Person() {
}
Here we put the student number and grade fields into the main constructor , This shows that you are right about Student Class instantiation , All parameters required in the constructor must be passed in .
such as :
val student = Student(“a123”, 5) So we've created one Student The object of , At the same time, specify the student number as a123, grade 5. in addition , Because the parameters in the constructor are passed in when the instance is created , It doesn't have to be reassigned as before , Therefore, we can declare all parameters as val. You may ask , The primary constructor has no body , If I want to write some logic in the main constructor , What to do ?
Kotlin It provides us with a init Structure , All the logic in the main constructor can be written in it :
class Student(val sno: String, val grade: Int) : Person() {
init {
println("sno is " + sno)
println("grade is " + grade)
}
}
constructor Construct method keywords The above example In the absence of other keyword modifiers After declaring a class, you can directly use parentheses to represent constructor parameters If there are other keywords You need to add constructor
Such as : class Person constructor(username: String, age: Int){}
Other constructor declarations :
constructor(context: Context) : this(context, null) {
mContext = context
}
Be careful : Any class can only have one primary constructor , But you can have multiple secondary constructors , The secondary constructor can also be used to instantiate a class , And the secondary constructor has a function body .
The secondary constructor is by constructor Keywords to define .
kotlin Specified in the , When a class has both primary and secondary constructors , All secondary constructors must call the primary constructor ( Including indirect calls )
Rewriting methods override keyword
for example : override fun onDraw(canvas: Canvas) {}
when Conditional statements
fun getScore(name: String) = if (name == "Tom") {
86
} else if (name == "Jim") {
77
} else if (name == "Jack") {
95
} else if (name == "Lily") {
100
} else {
0
}
Here's a definition getScore() function , This function receives a student name parameter , And then through if Judge to find the corresponding test score of the student and return . You can see , The syntax of the single line code function is used again
Although the above code can really achieve the function we want , But I wrote so much if and else, Do you think the code is redundant ? you 're right , When you have a lot of judgment conditions , We should consider using when At the time of statement , Now let's write the code as follows :
fun getScore(name: String) = when (name) {
"Tom" -> 86
"Jim" -> 77
"Jack" -> 95
"Lily" -> 100
else -> 0
}
when Statement and if The sentence is the same , It can also have a return value , Therefore, we can still use the syntax of single line code functions .
when Statement allows you to pass in a parameter of any type , Then you can go to when A series of conditions are defined in the structure of , The format is :
Match the value -> { Perform logical }
When your execution logic has only one line of code ,{ } It can be omitted .
In addition to exact matching ,when Statement also allows type matching . What is type matching ? Let me give you another example .
Define a checkNumber() function , As shown below :
fun checkNumber(num: Number) {
when (num) {
is Int -> println("number is Int")
is Double -> println("number is Double")
else -> println("number not support")
}
}
is Keywords are the core of type matching , It is equivalent to Java Medium instanceof keyword . because checkNumber() Function receives a Number Parameters of type , This is a Kotlin A built-in abstract class , image Int、Long、Float、Double And other classes related to numbers are its subclasses , Therefore, type matching can be used here to determine what type the incoming parameters belong to , If it is Int Type or Double type , Print the type , Or call
The type of this parameter is not supported .
Modifier

边栏推荐
- Analysis of the multiple evaluation system of children's programming
- Qt编译出错ERROR: Unknown module(s) in QT: script
- Review of the paper: unmixing based soft color segmentation for image manipulation
- 请求对象,发送请求
- Create a nonlinear least squares test in R
- 使用IDEA画结构图
- Analysis of technological changes in social robots
- 解析创客空间机制建设的多样化
- Survival analysis based on ovarian data set
- Please advise tonghuashun which securities firm to choose for opening an account? Is it safe to open an account online?
猜你喜欢

Classic quotations from "human nature you must not know"

经典模型——NiN&GoogLeNet

小米电视的网页和珠宝的网页

Hardware creation principle of campus maker space

项目部署遇到的问题-生产环境

Network PXE starts winpe and supports UEFI and legacy boot

How to prompt

解析创客空间机制建设的多样化

Utonmos: digital collections help the inheritance of Chinese culture and the development of digital technology

Inkscape如何将png图片转换为svg图片并且不失真
随机推荐
渐变
Butterknife unbinder uses flashback in fragment and viewpager
ArrayList#subList这四个坑,一不小心就中招
Clion项目中运行多个main函数
Lumen Analysis and Optimization of ue5 global Lighting System
Stm32cubemx: watchdog ------ independent watchdog and window watchdog
360 秒了解 SmartX 超融合基础设施
Oracle connectivity issues and Solutions
Using meta analysis to drive the development of educational robot
Authorization of database
如何提词条
给网站添加“开放搜索描述“以适配浏览器的“站点搜索“
HL7Exception: Can‘t XML-encode a GenericMessage. Message must have a recognized struct
浅谈虚拟内存与项目开发中的OOM问题
【论文笔记】Supersizing Self-supervision: Learning to Grasp from 50K Tries and 700 Robot Hours
Analysis and optimization of ue5 global illumination system lumen
论文回顾:Unmixing-Based Soft Color Segmentation for Image Manipulation
Preparation for wechat applet development
Wealth freedom skills: commercialize yourself
关于#sql#的问题:SQL问题--账号多地登录的SQL代码