Quantcast
Channel: CSDN博客移动开发推荐文章
Viewing all articles
Browse latest Browse all 5930

4.2 Kotlin 语法精简版(2)

$
0
0

4.2 Kotlin 语法精简版(2)

创建数据对象(POJOs/POCOs)

data class Customer(val name: String, val email: String)

提供一个Customer类,有下列功能:

  • getters 给所有的属性(setters 如果有变量的话vars
  • equals()
  • hasCode()
  • toString()
  • copy()
  • component1(), component2(), … 等所有的属性

函数参数默认值

fun foo(a: Int = 0, b : String= "") {...}

过滤一个列表

val positives = list.filter { x -> x > 0 }

或者这样写更短

val positives = list.filter { it > 0 }

字符串插值

println(“Name $name”)

对象检查

when (x) {
    is Foo -> ...
    is Bar -> ...
    else    -> ...
}

遍历一个键值对的map/list

for ((k, v) in map) {
    println("$k -> $v")
}

K, V 可以任何类型

使用ranges

for ( i in 1..100) { ... } // closed range: include 100
for ( i in 1 until 100) { ... } // half-open range: does not include 100
for ( x in 2..10 step 2) { ... }
for ( x in 10 downTo 1) { ... }
if( x in 1..10) { ... }

只读列表

val list = listOf("a", "b", "c")

只读map

val map = mapOf("a" to 1, "b" to 2, "c" to 3")

访问一个map

println(map["key"])
map["key"]=value;

println(map["a"])
val key = "b"
println(map["$key"])

延迟加载的属性

val p: String by lazy {
    // compute the string
}

函数扩展

fun String.spaceToCamelCase() { ... }
"Convert this to camelcase".spaceToCamelCase()

创建单例

object Resource {
    val name = "Name"
}

if not null and else 简写

val files = File("Test")listFiles()
println(files?.size ?: "empty")

if null 执行某代码

val data = ...  
val email = data["mail"] ?: throw IllegalStateException("Email is missing!")

if not null 执行某代码

val data = ...
data?.let {
    ... // execute this block if not null
}

使用when语句return

fun transform(color: String): Int {
    return when (color) {
        "Red" -> 0
        "Green" -> 1
        "Yellow" -> 2
        else -> throw IllegalArgumentException("Invalid color param value")
    }
}

try/catch 语句

fun test() {
    val result = try {
        count()
    } catch (e : ArithmeticException) {
        throw IllegalStateException(e)
    }
    // working with the result
}

if 语句

fun foo(param: Int) {
    val result = if (param == 1) {
        "one"
    } else if (param == 2) {
        "two"
    } else { 
        "three"
    }
}

返回值使用’builder-style’

fun arrayOfminusOnes(size: Int): IntArray {
    return IntArray(size).apply { fill(-1) }
}

单表达式函数

fun theAnswer() = 42

这和下面是一样的

fun theAnswer() {
    return 42
}

这可以和其他范式组合使用,写出更短的代码,例如和when一起使用:

fun transform(color: String): Int = when (color) {
    "Red" -> 0
    "Green" -> 1
    "Yellow" -> 2
    else -> throw IllegalArgumentException("Invalid color param value")
}
## 使用`with` 语法调用对象的多个方法
```kotlin
class Turtle {
    fun penDown()
    fun penUp() 
    fun turn(degree: Double)
    fun forward(pixels: Double)
}

val myTurtle = Turtle()
with(myTurtle) { // draw a 100 pixel square
    penDown()
    for ( i in 1..4) {
        forward(100.0)
        turn(90.0)
    }
}




<div class="se-preview-section-delimiter"></div>

try 语句块

val stream = Files.newInputStream(Paths.get("/some/file.txt"))
stream.buffered().reader().use { reader ->
    println(reader.readText())
}




<div class="se-preview-section-delimiter"></div>

泛型方法使用泛型参数,并返回泛型

//  public final class Gson {
//     ...
//     public <T> T fromJson(JsonElement json, Class<T> classOfT) throws JsonSyntaxException {
//     ...
inline fun <reified T: Any> Gson.formJson(json): T = this.fromJson(json, T::class.java)




<div class="se-preview-section-delimiter"></div>

判断一个可能为空的Bolean

val b: Boolean? = ...
if (b == true) {
    ...
} else {
    // 'b' is false or null
}
作者:farmer_cc 发表于2017/6/5 7:10:55 原文链接
阅读:14 评论:0 查看评论

Viewing all articles
Browse latest Browse all 5930

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>