当前位置:网站首页>kotlin快速上手
kotlin快速上手
2022-06-26 02:46:00 【Azadoo】
val + 变量名:final类型对象
var + 变量名:普通对象
声明并初始化:val + 变量名 = 类()
val mLintPaint = Paint()
定义变量时,可在类型后面加一个问号?,表示该变量是Nullable,不加表示该变量不可为null。如下:
var s:String? = null
var s2:String = “xxx” //如果该变量被赋值为null,则编译不通过
声明数组:
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(“人类”, “高质量”, “码农”)
lateinit 关键字:
- lateinit var只能用来修饰类属性,不能用来修饰局部变量,并且只能用来修饰对象,不能用来修饰基本类型(因为基本类型的属性在类加载后的准备阶段都会被初始化为默认值)。
- lateinit var的作用也比较简单,就是让编译期在检查时不要因为属性变量未被初始化而报错。
- Kotlin相信当开发者显式使用lateinit var 关键字的时候,他一定也会在后面某个合理的时机将该属性对象初始化的
示例:声明未实例化的对象
lateinit var name: String
方法
常规:fun + 方法名(){}
带返回值的方法:
fun methodName(param1: Int, param2: Int): Int {
return 0
}
继承
再kotlin中 类默认是不允许被继承的 如果要设置成能被继承的类 需要open关键字
如:open class Person { ... }
比如继承View直接使用:代替extends 同时直接声明了构造方法
class ClassName(context: Context?) : View(context) {}
任何一个面向对象的编程语言都会有构造函数的概念,Kotlin中也有,但是Kotlin将构造函数分成了两种:主构造函数和次构造函数。
主构造函数将会是你最常用的构造函数,每个类默认都会有一个不带参数的主构造函数,当然你也可以显式地给它指明参数。主构造函数的特点是没有函数体,直接定义在类名的后面即可。比如下面这种写法:
class Student(val sno: String, val grade: Int) : Person() {
}
这里我们将学号和年级这两个字段都放到了主构造函数当中,这就表明在对Student类进行实例化的时候,必须传入构造函数中要求的所有参数。
比如:
val student = Student(“a123”, 5)这样我们就创建了一个Student的对象,同时指定该学生的学号是a123,年级5。另外,由于构造函数中的参数是在创建实例的时候传入的,不像之前的写法那样还得重新赋值,因此我们可以将参数全部声明成val。你可能会问,主构造函数没有函数体,如果我想在主构造函数中编写一些逻辑,该怎么办呢?
Kotlin给我们提供了一个init结构体,所有主构造函数中的逻辑都可以写在里面:
class Student(val sno: String, val grade: Int) : Person() {
init {
println("sno is " + sno)
println("grade is " + grade)
}
}
constructor构造方法关键字 如上例子 在没有其他关键字修饰的情况 声明类后可直接括号代表构造方法参数 如果有其他关键字 则需要加上constructor
如: class Person constructor(username: String, age: Int){}
其他构造方法声明方式:
constructor(context: Context) : this(context, null) {
mContext = context
}
注意:任何一个类只能有一个主构造函数,但可以有多个次构造函数,次构造函数也可以用于实例化一个类,且次构造函数是有函数体的。
次构造函数是通过constructor关键字来定义的。
kotlin中规定,当一个类既有主构造函数又有次构造函数时,所有的次构造函数都必须调用主构造函数(包括间接调用)
重写方法 override 关键字
例如: override fun onDraw(canvas: Canvas) {}
when条件语句
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
}
这里定义了一个getScore()函数,这个函数接收一个学生姓名参数,然后通过if判断找到该学生对应的考试分数并返回。可以看到,这里再次使用了单行代码函数的语法糖
虽然上述代码确实可以实现我们想要的功能,但是写了这么多的if和else,你有没有觉得代码很冗余?没错,当你的判断条件非常多的时候,就是应该考虑使用when语句的时候,现在我们将代码改成如下写法:
fun getScore(name: String) = when (name) {
"Tom" -> 86
"Jim" -> 77
"Jack" -> 95
"Lily" -> 100
else -> 0
}
when语句和if语句一样,也是可以有返回值的,因此我们仍然可以使用单行代码函数的语法糖。
when语句允许传入一个任意类型的参数,然后可以在when的结构体中定义一系列的条件,格式是:
匹配值 -> { 执行逻辑 }
当你的执行逻辑只有一行代码时,{ }可以省略。
除了精确匹配之外,when语句还允许进行类型匹配。什么是类型匹配呢?这里我再举个例子。
定义一个checkNumber()函数,如下所示:
fun checkNumber(num: Number) {
when (num) {
is Int -> println("number is Int")
is Double -> println("number is Double")
else -> println("number not support")
}
}
is关键字就是类型匹配的核心,它相当于Java中的instanceof关键字。由于checkNumber()函数接收一个Number类型的参数,这是Kotlin内置的一个抽象类,像Int、Long、Float、Double等与数字相关的类都是它的子类,所以这里就可以使用类型匹配来判断传入的参数到底属于什么类型,如果是Int型或Double型,就将该类型打印出来,否则就打
印不支持该参数的类型。
修饰符

边栏推荐
- 经典模型——ResNet
- How to add a regression equation to a plot in R
- Possible values for @supply in kotlin
- 解析少儿编程的多元评价体系
- 关于#sql#的问题:SQL问题--账号多地登录的SQL代码
- DF reports an error stale file handle
- 在 R 中创建非线性最小二乘检验
- Can the main RF circuit be removed for projects that do not need the main RF?
- Mysql常用sql语句之修改表名、删除表、获取表信息、删除指定日期的表记录
- 双碳红利+基建大年 | 图扑深耕水利水电绿色智能装备领域
猜你喜欢

《你不可不知的人性》經典語錄

Redis configuration and optimization of NoSQL
![[solution] the blue screen restart problem of the virtual machine started by the VMware of Lenovo Savior](/img/c3/892ce2f45abea7140df98cabc1431b.png)
[solution] the blue screen restart problem of the virtual machine started by the VMware of Lenovo Savior

图扑软件数字孪生海上风电 | 向海图强,奋楫争先

Install development cross process communication

【论文笔记】Supersizing Self-supervision: Learning to Grasp from 50K Tries and 700 Robot Hours

附加:HikariCP连接池简述;(并没有深究,只是对HikariCP连接池有个基本认识)

Fresh graduates talk about their graduation stories

Utonmos adheres to the principle of "collection and copyright" to help the high-quality development of traditional culture

Good news | congratulations on the addition of 5 new committers in Apache linkage (incubating) community
随机推荐
Notes on the 3rd harmonyos training in the studio
Drawing structure diagram with idea
Simple use example of Aidl
Learn Tai Chi Maker - mqtt (IV) server connection operation
Survival analysis based on ovarian data set
小 P 周刊 Vol.10
数据库查询语句SQL中like、%、-的区别
【flask入门系列】flask处理请求和处理响应
在哪里开基金帐户安全?
NoSQL之Redis配置与优化
GD32 ADC采集电压
Golang regexp package use - 06 - other usage (Special Character conversion, find regular Common prefix, Switch gourmand mode, query regular Group NUMBER, query regular Group name, cut with regular, qu
Translation notes of orb-slam series papers
经典模型——ResNet
MySQL updates records based on the queried data
Authorization of database
我在中山,到哪里开户比较好?网上开户是否安全么?
【解决】CMake was unable to find a build program corresponding to “Unix Makefiles“.
MySQL根据查询的数据更新记录
Gd32 ADC acquisition voltage