2017-05-20 | work

kotlin share

本周五轮到技术分享,趁着 Google I/O 刚宣布 Kotlin 加入官方支持,正好借这个时机向同事们安利 Kotlin。选了几点内容,发现和这篇官方博客重合度蛮高的,膨胀一波不过分吧兄弟。不过这位老哥也没介绍 Delegation,Dsl,Coroutines …难道和我一样想偷懒


Kotlin

Statically typed programming language for modern multiplatform applications
100% interoperable with Java™ and Android™

Kotlin has been around for quite a while; it was announced back in 2011 and the first preview was released in 2012. Kotlin 1.0 was released in 2016, at which point JetBrains committed to maintaining backwards compatibility for stable features from 1.0 forward.

优势

  • 简洁
  • 安全
  • 兼容性
  • 强大的开发工具

与 Java 区别

  • class 默认 final
  • 没有原始类型
  • Collections 分为可变和不可变更两种
  • Exceptions
  • 没有 static 成员

Hello World

1
2
3
4
5
6
7
8
package hello

fun main(args: Array<String>) {
println("Hello World!")
}

var name:String = ""
val name:String = ""

一些简单的语言特性

Null-checks

1
2
3
4
5
6
var email:String = null // Error
var name:String? = null
fun saveName(name:String){
...
}
saveName(name) // Error

Data Class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
public class Customer {
private String name;
private String email;
private String company;

public Customer(String name) {
this(name, "", "");
}

public Customer(String name, String email) {
this(name, email, "");

}

public Customer(String name, String email, String company) {
this.name = name;
this.email = email;
this.company = company;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getCompany() {
return company;
}

public void setCompany(String company) {
this.company = company;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;

Customer customer = (Customer) o;

if (name != null ? !name.equals(customer.name) : customer.name != null) return false;
if (email != null ? !email.equals(customer.email) : customer.email != null) return false;
return company != null ? company.equals(customer.company) : customer.company == null;
}

@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (email != null ? email.hashCode() : 0);
result = 31 * result + (company != null ? company.hashCode() : 0);
return result;
}

@Override
public String toString() {
return "Customer{" +
"name='" + name + '\'' +
", email='" + email + '\'' +
", company='" + company + '\'' +
'}';
}
}


1
2
data class Customer(var name: String, var email: String = "",
var company: String = "")

Smart casts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
interface Cpu

class Intel : Cpu {
fun intelCool() {}
}
class AMD : Cpu {
fun amdBoom() {}
}

val cpu: Cpu = AMD()

if (cpu is Intel) {
cpu.intelCool()
} else if (cpu is AMD) {
cpu.amdBoom()
}

when

1
2
3
4
5
6
7
when (obj) {
1 -> println("One")
"Hello" -> println("Greeting")
is Long -> println("Long")
!is String -> println("Not a string")
else -> println("Unknown")
}

Extension functions

1
2
3
4
5
fun String?.isNull(): Boolean {
return this == null
}
var name: String? = null
println(name.isNull()) // ok
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
fun Cpu.go() {
print("cpu go")
}

fun Intel.go() {
print("intel go")
}

fun AMD.go() {
print("amd go")
}

fun main(args: Array<String>) {
val cpu: Cpu = AMD()

cpu.go()
}

Destructuring Declarations

1
2
3
4
5
6
7
8
data class Order(val itemCode: String, val quantity: Int,
val price: Float)
fun getOrder(...): Order {
...
return Order(itemCode, quantity, price);
}

val (what, howMany, howMuch) = getOrder(...)

Higher-Order Functions and Lambdas

A higher-order function is a function that takes functions as parameters, or returns a function.

1
2
3
4
5
6
7
8
9
fun <T> lock(lock: Lock, body: () -> T): T {
lock.lock()
try {
return body()
}
finally {
lock.unlock()
}
}

object

1
2
3
4
5
6
7
8
9
10
// The use of 'object' instead of 'class' indicates a singleton declaration
object Singleton {
fun foo() = 42
}

// 匿名内部类
val arrayList = arrayListOf(1, 5, 2)
Collections.sort(arrayList, object : Comparator<Int> {
override fun compare(x: Int, y: Int) = y - x
})


Android

Kotlin Android Extensions

1
2
3
4
5
6
7
8
9
10
11
// Using R.layout.activity_main from the main source set
import kotlinx.android.synthetic.main.activity_main.*

class MyActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
textView.setText("Hello, world!")
// Instead of findView(R.id.textView) as TextView
}
}

Anko

1
2
3
4
5
6
verticalLayout {
val name = editText()
button("Say Hello") {
onClick { toast("Hello, ${name.text}!") }
}
}


参考