语言风格
这里整理了 kotlin 惯用的代码风格,如果你有喜爱的代码风格,可以在 github 上给 kotlin 提 pull request 。
创建 DTOs(POJSs/POCOs) 文件:
- data class Customer(val name: String, val email: String)
上述代码提供了一个包含以下功能的 Customer 类:
- equals()
- hashCode()
- toString()
- copy()
,
- component1()
, …, 等等 (请查看 Data classes)
- component2()
函数参数默认值:
- fun foo(a: Int = 0, b: String = "") {...
- }
过滤一个 List:
- val positives = list.filter {
- x - >x > 0
- }
还可以更简洁:
- val positives = list.filter {
- it > 0
- }
$ 操作符给字符串中插入变量 :
- println("Name $name")
类型实例检查:
- 1 when (x) {
- 2 is Foo -> ...
- 3 is Bar -> ...
- 4 else -> ...
- 5 }
Map/List 的名值对遍历:
- 1
- for ((k, v) in map) {
- 2 println("$k -> $v") 3
- }
k, v 的命名可以是任何字符
使用 Ranges(区间):
- 1
- for (i in 1..100) {...
- } // 闭区间: 包含 100
- 2
- for (i in 1 until 100) {...
- } // 半开区间: 不包含 100
- 3
- for (x in 2..10 step 2) {...
- } // x自增2
- 4
- for (x in 10 downTo 1) {...
- } // 倒序遍历
- 5
- if (x in 1..10) {...
- } // x是否在区间
只读 List:
- val list = listOf("a", "b", "c")
只读 Map:
- 1 val map = mapOf("a" to 1, "b" to 2, "c" to 3)
访问 Map:
- 1println(map["key"])
- 2map["key"] = value
lazy 属性:
- 1 val p: String by lazy {
- 2 // compute the string
- 3
- }
函数扩展:
- 1 fun String.spaceToCamelCase() { ... }
- 2
- 3"Convert this to camelcase".spaceToCamelCase()
创建单例:
- 1 object Resource {
- 2val name = "Name"3}
if 判空 (null) 的快捷方式:
- 1val files = File("Test").listFiles()
- 2
- 3println(files?.size)
有 else:
- 1val files = File("Test").listFiles()
- 2
- 3println(files?.size ?: "empty")
如果为空则执行语句:
- 1val data = ...
- 2val email = data["email"] ?:throwIllegalStateException("Email is missing!")
为空则执行操作:
- 1val data = ...
- 2
- 3data.let {
- 4...// execute this block if not null
- 5}
在 when 语句里返回:
- 1 fun transform(color: String) : Int {
- 2
- return when(color) {
- 3 "Red" - >0 4 "Green" - >1 5 "Blue" - >2 6
- else - >
- throw IllegalArgumentException("Invalid color param value") 7
- }
- 8
- }
try/catch:
- 1 fun test() {
- 2 val result =
- try {
- 3 count() 4
- } catch(e: ArithmeticException) {
- 5
- throw IllegalStateException(e) 6
- }
- 7 8 // Working with result
- 9
- }
IF:
- 1 fun foo(param: Int) {
- 2 val result =
- if (param == 1) {
- 3 "one"4
- } else if (param == 2) {
- 5 "two"6
- } else {
- 7 "three"8
- }
- 9
- }
生成器模式写法返回 Unit :
- 1 fun arrayOfMinusOnes(size: Int) : IntArray {
- 2
- return IntArray(size).apply {
- fill( - 1)
- }
- 3
- }
单行表达式:
- fun theAnswer() = 42
相当于:
- 1 fun theAnswer() : Int {
- 2
- return 42 3
- }
可以高效地与其他语法配合,是代码更简洁,如下面的 when :
- 1fun transform(color: String): Int = when (color) {
- 2"Red" -> 03"Green" -> 14"Blue" -> 25 else->throwIllegalArgumentException("Invalid color param value")
- 6}
使用 With 语句可以调用一个对象里的多个方法:
- 1 class Turtle {
- 2 fun penDown()
- 3 fun penUp()
- 4 fun turn(degrees: Double)
- 5 fun forward(pixels: Double)
- 6 }
- 7
- 8val myTurtle = Turtle()
- 9with(myTurtle) {//draw a 100 pix square
- 10 penDown()
- 11 for(i in 1..4) {
- 12forward(100.0)
- 13turn(90.0)
- 14 }
- 15 penUp()
- 16}
支持 Java 7 的文件操作方式:
- 1val stream = Files.newInputStream(Paths.get("/some/file.txt"))
- 2stream.buffered().reader().use { reader ->3 println(reader.readText())
- 4}
为声明需要泛型信息的泛型方法提供更为方便的格式:
- 1 // public final class Gson {
- 2 // ...
- 3 // public <T> T fromJson(JsonElement json, Class<T> classOfT) throws JsonSyntaxException {
- 4 // ...
- 5
- 6inline fun Gson.fromJson(json): T = this.fromJson(json, T::class.java)
Boolean 值可以是 null:
- 1 val b: Boolean ? =...2
- if (b == true) {
- 3...4
- } else {
- 5 // `b` is false or null
- 6
- }
来源: http://www.cnblogs.com/joejs/p/6878128.html