Kotlin之从入门到放弃
var:变量
val:常量
声明变量\常量:
var code: Int = 0
var isSuccess: Boolean = false
var message: String? = null
//空安全变量
var str: String = "hello"
//常量数组int[][][] arrs = new int[3][2][1];
val arrs = Array(3) { Array(2) { IntArray(1) } }
条件:
- if else 同java一样
- java的switch ==> kotlin的when ,when子式可以是各种返回Boolean的表达式
val x = 7
when (x) {
in 1..10 -> print("x is in the range")
in validNumbers -> print("x is valid")
!in 10..20 -> print("x is outside the range")
else -> print("none of the above")
}
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
val currentTime = System.currentTimeMillis()
if (currentTime - lastTime < 500) {
lastTime = currentTime
return true
} else {
lastTime = currentTime
}
}
}
return super.onTouchEvent(event)
}
3.循环
while 和 do...while 同Java一样;
for有变化
val list = ArrayList<String>()
//递增for (int i = 0; i < list.size(); i++)
for (i in list.indices) {
print(list[i])
}
//递增for (int i = 2; i < list.size(); i++)
for (i in 2..list.size-1) {
print(list[i])
}
//递减for (int i = list.size(); i >= 0; i--)
for (i in list.size downTo 0) {
print(list[i])
}
//操作列表内的对象
for (item in list) {
print(item)
}
//加强版
for((i, item) in list.witnIndex()) {
print(list[i])
print(item)
}
//变种版
list.forEach {
print(it)
}
list.forEach {
print(it)
}
list.forEachIndexed { i, s ->
print(list[i])
print(s)
}
list.forEachIndexed(object :(Int,String) -> Unit{
override fun invoke(i: Int, s: String) {
print(list[i])
print(s)
}
})
冒号用法
//val表示常量var表示变量声明
val name: String = "tutu"
//省略类型说明
var age = "23"
//fun表示函数
fun getName(): String{
return "tutu"
}
//类继承
class UserList<E>(): ArrayList<E>() {
//...
}
//java类写成 类名::class.java
val intentGo = Intent(this@MainActivity, RegisterActivity::class.java)
@用法
它告诉你 this 和 return 指的是哪一个
Toast.makeText(this@CaptchaActivity, resources.getText(R.string.please_input_correct_captcha), Toast.LENGTH_LONG).show()
valintentGo=Intent(this@MainActivity,RegisterActivity::class.java)
startActivity(intentGo)
class User {
inner class State{
fun getUser(): User{
//返回User
return this@User
}
fun getState(): State{
//返回State
return this@State
}
}
}
bean类的get set方法省略
class BannerBean {
var code: Int = 0
var isSuccess: Boolean = false
var message: String? = null
var data: List<DataBean>? = null
class DataBean {
var id: Int = 0
var bannerUrl: String? = null
var forwardUrl: String? = null
var bannerSource: String? = null
}
}
//赋值
val bannerBean =BannerBean ()
bannerBean .message="我是message"
bannerBean .code=1
//取值
val message=bannerBean .message
val code=bannerBean .code=1
$赋值
Log.i("wzx",message:${bannerBean .message})
//输出
message:我是message
空判断
//类型后面加?表示可为空
var age: String? = "23"
//抛出空指针异常
val ageInt = age!!.toInt()
//不做处理跳过
val ages = age?.toInt()
权限
Java中内部类和参数默认为为private,Kotlin内部类和参数默认为public;
类默认为不可继承(final),想要可被继承要声明为 open 或 abstract;
取消了static关键字,静态方法和参数统一写在 companion object 块;
internal模块内可见,inner内部类。