Kotlin开发之旅《二》—Kotlin的基本语法
今天来学习Kotlin的基本语法。以Jaiva to Kotlin 为主,以便于快速认识 Kotlin 这门语言
于亚豪的博客地址:
http://blog.csdn.net/androidstarjack/article/details/73252595
如果对Kotlin不太了解的童鞋们,请参考
Kotlin成为Android开发首选语言——你绝对不能错过的
今天来学习Kotlin的基本语法。以Jaiva to Kotlin 为主,以便于快速认识 Kotlin 这门语
1、变量的声明
定义局部变量
赋值(只读)及局部变量
val a: Int = 1 // ⽴即赋值
val b = 2 // ⾃动推断出 `Int` 类型
val c: Int // 如果没有初始值类型不能省略
c = 3 // 明确赋值
// a = b + c; 写法错误可变变量
var x = 5 // ⾃动推断出 `Int` 类型
x += 1
2、 使⽤条件表达式
fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}
//使⽤ if 作为表达式:
fun compare(a: Int, b: Int) = if (a > b) a else b
3、使用可传空值及 null 检测
fun parseInt(str: String): Int? {
var length : Int? = 0;
if(str != null){
length = str.length;
}
return length;
}
fun parseString(content : String) :String ?{
return content;
}
eg:
fun printProduct(arg1: String, arg2: String) {
val x = parseInt(arg1)
val y = parseInt(arg2)
// 直接使⽤ `x * y` 可能会报错,因为他们可能为 null
if (x != null && y != null) {
// 在空检测后,x 和 y 会⾃动转换为⾮空值(non-nullable)
println(x * y)
}
else {
println("either '$arg1' or '$arg2' is not a number")
}
}
fun printProduct2(arg1: String, arg2: String) {
val x = parseInt(arg1)
val y = parseInt(arg2)
if (x == null) {
println("Wrong number format in arg1: '${arg1}'")
return
}
if (y == null) {
println("Wrong number format in arg2: '${arg2}'")
return
}
// 在空检测后,x 和 y 会⾃动转换为⾮空值
println(x * y)
}
4、for循环的使用
基本遍历
fun useForListMap(){ //实例化list计划 ar list = listOf("终端","研发部","欢迎","你"); //遍历list for (content in list){ println(content); } //遍历 方法2 for (content in list.indices){ println("------"+list[content]); println(content); } }
Java
if (value >= 0 && value <= 100) {} for (int i = 1; i <= 100 ; i++) {} for (int i = 1; i < 100 ; i++) {} for (int i = 100; i >= 0 ; i--) {} for (int i = 1; i <= 100 ; i+=2) {} for (int i = 100; i >= 0 ; i-=2) {}
Kotlin
if (value is 0..100) { } for (i in 1..100 ) {} for (i in 1 until 100) {} // 半开区间:不包含 100 for (i in 100 downTo 0) {} for (i in 1..100 step 2) {} for (i in 100 donwTo 1 step 2) {}
Java
List<String> list = Arrays.asList("java", "c++", "Android", "Kotlin", "iOS"); for(int i = 0; i < list.size(); i++ ) { list.set(i, "Hello " + list.get(i)); if (!list.get(i).contains("c")) { System.out.println(list.get(i)); } } //输出: // Hello java // Hello Android // Hello Kotlin // Hello iOS
Kotlin
var list = arrayOf("java", "c++", "Android", "Kotlin", "iOS") list.map { "Hello $it" }.filter { !it.contains("c") }.forEach { println(it) } //输出: // Hello java // Hello Android // Hello Kotlin // Hello iOS
只读 list
val list = listOf("a", "b", "c")
访问 map
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
println(map["key"])
map["key"] = value
延迟属性
val p: String by lazy {
// 计算该字符串
}
扩展函数
fun String.spaceToCamelCase() { …… }
"Convert this to camelcase".spaceToCamelCase()
创建单利
object Resource {
val name = "Name"
}
返回when 表达式
fun transform(color: String): Int { return when (color) { "Red" -> 0 "Green" -> 1 "Blue" -> 2 else -> throw IllegalArgumentException("Invalid color param value") } }
“try/catch”
fun test() {
val result = try {
count()
} catch (e: ArithmeticException) {
throw IllegalStateException(e)
}
// 使⽤ result
}
“if” 表达式
fun foo(param: Int) {
val result = if (param == 1) {
"one"
} else if (param == 2) {
"two"
} else {
"three"
}
}
函数
Java
public final void func() {} public final int func(int value) { return 1 * value; }
Kotlin
fun func() {} fun func(value: Int): Int { return 1 * value }
// 或者
fun func(value: Int): Int = 1 * value
类
Java
public final class Person { private String name = null; private int age = 25; private Person() { } public Person(String name, int age) { this.name = name; this.age = age; } }
Kotlin
class Person private constructor() { private var name: String? = null private var age: Int = 25 constructor (name: String, age: Int): this() { this.name = name this.age = age } }
静态方法( 伴生对象 )
Java
public final class Manager { private Manager() {} public static Manager getInstance () { return new Manager(); } }
Kotlin
class Manager private constructor() { companion object { fun getInstance(): Manager = Manager() } }
实体类
java
public class Person { public String name; public age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; if (age != person.age) return false; return name != null ? name.equals(person.name) : person.name == null; } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + age; return result; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
Kotlin
data class Person(var name: String, var age: Int)
解构
Java
Person p = new Person("haohao", 25); String name = p.getName(); String age = p.getAge();
Kotlin
var p = Person("name", 25) var (name, age) = p
接口
Java
interface Readable { String getContent(); } public final class Book implements Readable { @override public String getContent() { return "Hello"; } }
Kotlin
// Kotlin 接口中可以设置抽象和非抽象方法,可以有属性但必须声明为抽象或提供访问器实现。 interface Readable { fun getContent(): String fun getVersion(): Int = 0 } class Book(): Readable { override fun getContent(): String = "Hello" override fun getVersion(): Int { return super.getVersion() } }
继承
Java
public class Person { private String name = null; public Person(String name) { this.name = name; } public void sayHello() { System.out.println("Hello"); } public final void sayGood() { System.out.println("Good"); } } public final class Student extends Person { private String school = null; public Student(String name, String school) { this.school = school; super(name); } @override public void sayHello() { super.sayHello(); System.out.println("Hello Student"); } }
Kotlin
open class Person(private var name: String? = null) { open fun sayHello() = println("Hello") fun sayGood() = println("Good") } class Student(private var school: String? = null, name: String): Person(name) { override fun sayHello() { super.sayHello() println("Hello Student") } }
静态与非静态内部类
Java
public final class Outer { private int bar = 100; public static class Nester { public final String foo() { return "Hello Kotlin!"; } } public final class Inner { public final int foo() { return bar; // 可以访问外部类成员 } } } System.out.println(new Outer.Nester().foo()); // System.out.println(new Outer().Inner().foo()); 不能在其他类中实例化非静态内部类
Kotlin
class Outer { private var bar: Int = 100 // 嵌套类 class Nester { // 不能访问外部类成员 fun foo() = "Hello Kotlin!" } // 内部类 inner class Inner { // 可以访问外部类成员 fun foo() = bar } } println(Outer.Nested().foo()) println(Outer().Inner().foo())
匿名内部类
Java
view.setOnClickListener(new OnClickListener() { @override onClick(View view){ // to do something. } });
Kotlin
interface OnClickListener { fun onClick() } class View(){ var listener: OnClickListener? = null fun setOnClickListener(listener: OnClickListener) { this.listener = listener } } view.setOnClickListener(object : OnClickListener{ override fun onClick() { TODO("not implemented") } })
泛型
Java
public final class Wrapper<T> { private T item; public Wrapper(T item) { this.item = item; } public T getItem() { return item; } } Wrapper<String> wrapper = new Wrapper<>("Hello Kotlin"); System.out.println(wrapper.getItem());
Kotlin
class Wrapper<T>(val item: T) var wrapper = Wrapper("Hello Kotlin") println(wrapper.item)
匿名函数 ( Lambda 表达式 )
Java (Java 8)
new Thread(() -> { System.out.println("Hello Kotlin"); }).start(); // 同下 new Thread(new Runnable() { @Override public void run() { System.out.println("Hello Kotlin"); } }).start();
Kotlin
Thread(Runnable { println("Hello Kotlin") }).start() // Kotlin Lambda 表达式语法 val sum = {x: Int, y: Int -> x + y } val sum1: (Int, Int) -> Int = {x, y -> x + y } val sum2 = fun(x: Int, y: Int): Int { return x + y } println(sum(2,8)) println(sum1(2,8)) println(sum2(2,8)) //输出: // 10 // 10 // 10 // Hello Kotlin
简单异步
Java (Java 8)
new Thread(() -> { data = DataSource.obtain(); //耗时操作 runOnUiThread(() -> { view.load(data); //更新 UI }); }).start();
Kotlin (Kotlin Anko)
async { data = DataSource.obtain(); //耗时操作 uiThread { view.load(data); //更新 UI } }
泛型函数
Java
// Java 不能单独实现泛型函数
Kotlin
fun <T> singletonList(item: T): List<T> { return arrayListOf(item) } val list = singletonList<String>("kotlin")
嵌套函数
Java
// Java 不支持嵌套函数
Kotlin
fun main(args: Array<String>) { fun sayHello() { println("Hello Kotlin") } sayHello(); } // 输出: // Hello Kotlin
Kotlin lazy 懒加载
Kotlin
val lazyValue: String by lazy { println("init") //第一次使用时才被初始化 "Hello Kotlin" } fun main(args: Array<String>) { println(lazyValue) println(lazyValue) } //输出: // init // Hello Kotlin // Hello Kotlin
Kotlin 闭包
闭包的理解
简单理解:闭包能够将一个方法作为一个变量去存储,这个方法有能力去访问所在类的自由变量。
Kotlin
val plus = {x: Int, y: Int -> println("$x plus $y is ${x+y}")} val hello = {println("Hello Kotlin")} fun main(args: Array<String>) { {x: Int, y: Int -> println("$x plus $y is ${x+y}") }(2, 8) // 自执行的闭包 plus(2, 8) hello() } //输出: // 2 plus 8 is 10 // 2 plus 8 is 10 // Hello Kotlin
Kotlin observable 观察者
Kotlin
class Person{ public var name: String by Delegates.observable("init .. "){ property,oldValue,newValue -> println("property : $property, oldValue : $oldValue, newValue : $newValue") } } fun main(args: Array<String>) { val person = Person() println(person.name) person.name = "haohao" person.name = "nannan" } //输出: // init .. // property : var Person.name: kotlin.String, oldValue : init .. , newValue : haohao // property : var Person.name: kotlin.String, oldValue : haohao, newValue : nannan
学习文档
官网文档:
http://kotlinlang.org/docs/reference/android-overview.html
官网:
http://kotlinlang.org/
国内中文文档:
https://huanglizhuo.gitbooks.io/kotlin-in-chinese/content/
国内中文文档2:
http://www.liying-cn.net/kotlin/docs/reference/
Kotlin-github地址
https://github.com/JetBrains/kotlin
这里学到的不仅仅是技术