Kotlin的学习
还记得两年前,小编的同事就在用kotlin代码写android应用了。我真的很佩服他的学习能力,三下五除二就把kotlin应用了起来。而如今小编才想起来学这个门语言。其实在小编脑海里有两个问题
1 学不学kotlin
毕竟学习一门自己不熟悉的语言需要花时间,每个人的学习能力也不一样,接收的时间也是不一样的。学不学的问题其实不用纠结。就两个选择:学和不学。
var 学: Boolean? = null
学 = true
if (学) {
你将获得一门新的技能,但是你需要花费更多的时间。
if (运用到项目中) {
学以致用
} else {
只是多了一门备用的技能
}
} else {
你将暂时不能掌握这门语言
}
2 怎么学
在小编看来,最好的教程就在官网,开始的时候跟着官网的demo来吧。
// 官方首页
https://kotlinlang.org
// 官方文档地址
https://kotlinlang.org/docs/reference/
以下是小编今天整理的一些基础知识。入门必备
定义基本数据类型
Numbers
这个和其他语言差不多,有Byte Short Int Long 他们分别是8、16、32、64位。
还有Float 和Double,他们分别是32位和64位
定义的时候,需要用变量来赋值,这个时候可以用var 和val来定义
var是可变的,也就是它定义的变量可以多次赋值。val是只读的,只能赋值一次。变量可以直接写值,自动分配类型,也可以自己规定类型
//>var style="box-sizing: border-box; margin: 0px; padding: 0px; font-size: inherit; color: rgb(174, 135, 250); line-height: inherit; overflow-wrap: inherit !important; word-break: inherit !important;">1
style="box-sizing: border-box; margin: 0px; padding: 0px; font-size: inherit; color: rgb(174, 135, 250); line-height: inherit; overflow-wrap: inherit !important; word-break: inherit !important;">4
// two 不能赋值第2次,idea提示的是val cannot be reassigned
val two = 3
two = 5
kotin 会根据每次赋值的大小自己分配不同的Number类型
val style="box-sizing: border-box; margin: 0px; padding: 0px; font-size: inherit; color: rgb(174, 135, 250); line-height: inherit; overflow-wrap: inherit !important; word-break: inherit !important;">1 // Int
val threeBillion = 3000000000 // Long
val style="box-sizing: border-box; margin: 0px; padding: 0px; font-size: inherit; color: rgb(174, 135, 250); line-height: inherit; overflow-wrap: inherit !important; word-break: inherit !important;">1L // Long
// Byte需要规定类型,不然val默认为int
val style="box-sizing: border-box; margin: 0px; padding: 0px; font-size: inherit; color: rgb(248, 35, 117); line-height: inherit; overflow-wrap: inherit !important; word-break: inherit !important;">Byte = 1
// 在变量值后面加F或者f表示Float,不加则默认为double
val pi = 3.14 // Double
val e = 2.7182818284 // Double
val eFloat = 2.7182818284f // Float, actual value is 2.7182817
Characters
Char的定义
var c = 'd'
Booleans
这个类型是Boolean,他的值只有true和false
boolean可以进行操作和java一样,&& 、|| 、!
Arrays
数组类型通过Array来定义
Strings
字符串的操作String
// 单行字符串,通过转义的回车变多行
var s = "dhhah\n" +
"sssss"
// 多行字符的定义
s = """
hahaha
hahah
aha
aha
"""
定义包
包的声明应处于源文件顶部
// 包
package stone
// 引入的其他包
import other.getName
fun sayHello(hello: String) {
// 打印字符串
print(hello)
// 调用other.getName包中的方法
getName(hello)
}
定义函数
函数用fun表示
// 不带参数的函数
fun funName() {}
// 带参数的函数
fun funName(int: Type){}
//返回的函数
fun funName() : Type {
val type:Type
return type
}
// 如果只有一条语句,可以这样写代带返回的函数
fun funName()= statement
如果你觉得小编总结的对你有帮助,请转发给有需要的人,轻轻的点下在看也是对小编的支持。
扫描关注哦