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计划
var 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复制代码