https://developer.android.google.cn/kotlin/learn
1 继承 : xxx() 为什么有些不用写()
overide 下移到定义方法最前面
不用写 权限修饰词了如public private protect
eg:
class MyActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity)
}
}
public class MyActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
}
}
2 类型转换 : xx as JJ
接口回调方法无参数的可以省略
val fab = findViewById(R.id.fab) as FloatingActionButton
fab.setOnClickListener {
...
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
...
}
});
3 val var
4 Null 安全
val languageName: String? = null
5 条件语句
无三元运算符,使用的是条件表达式
从条件语句的复杂度到when(无需写break, -> 来分隔条件和内容
val answerString = when {
count == 42 -> "I have the answer."
count > 35 -> "The answer is close."
else -> "The answer eludes me."
}
println(answerString)
6 函数 TODO
简化函数为
下面的函数可以有两种变体
fun generateAnswerString(countThreshold: Int): String {
val answerString = if (count > countThreshold) {
"I have the answer."
} else {
"The answer eludes me."
}
return answerString
}
函数返回单个表达式的结果时,可以通过直接返回函数中包含的 if-else 表达式的结果来跳过声明局部变量
将 return 关键字替换为赋值运算符
怎么写一个构造函数无参和有参同时共存
class SoftWarePresenter(iSoftWareView: ISoftWareView)
匿名函数
高阶函数
7 类
8 在android项目中使用kotlin
// Project build.gradle file.
buildscript {
ext.kotlin_version = ‘1.3.30’
…
dependencies {
classpath “org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version”
}
}
// Inside each module using kotlin
apply plugin: ‘kotlin-android-extensions’
apply plugin: ‘kotlin-android’
…
dependencies {
implementation “androidx.core:core-ktx:1.0.1”
implementation “org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version”
}