快速上⼿ Kotlin
基础语法
var age: Int = 19
val name: String = "Tom"
var age = 19
val name = "Tom"
String?
String
string!!
var name: String = "Tom"
var name2: String? = "Tom"
name = name2 // name2大于name 不能这样赋值
name = name2!!
name2 = name
var name: String? = null
println(name?.length)
fun printLength(name: String){
println(name.length)
}
printLength(null)
函数基础语法
fun echo(name: String): String? {
println("$name")
return name
}
与 Java 代码互调
Java 与 Kotlin 交互的语法变化
// Utils.kt
fun echo(name: String) {
println("$name")
}
// Main.java
public static void main(String[] args) {
UtilsKt.echo("hello");
}
Java 与 Kotlin 交互的语法变化
object Test {
fun sayMessage(msg: String){
println(msg)
}
}
Test.INSTANCE.sayMessage("hello"); //kotlin code
Test.sayMessage("hello") //java code
TestMain.class //java code
TestMain::class.java //kotlin code
Kotlin 没有封装类
//java code
public interface AInterface {
void putNumber(int num);
void putNumber(Integer num);
}
//kotlin code
a.putNumber(100)
Kotlin 类型空值敏感
//kotlin code
fun sayMessage(msg: String) {
println(msg)
}
//java code
a.sayMessage(null)
//java code
String format(String str) {
return str.isEmpty() ? null : str;
}
//kotlin code
fun function(str: String) {
val fmt1 = format(str)
val fmt2:String = format(str)
val fmt3:String? = format(str)
}
Kotlin 没有静态变量与静态⽅法
object Test {
fun sayMessage(msg: String){
println(msg)
}
}
Test.INSTANCE.sayMessage("hello")
Test.sayMessage("hello")
object Test {
@JvmStatic
fun sayMessage(msg: String){
println(msg)
}
}