kotlin 语法糖

  1. Use of “when” Expression Instead of “switch”

    fun getDayOfWeek(day: Int): String {
        return when (day) {
            1 -> "Monday"
            2 -> "Tuesday"
            3 -> "Wednesday"
            4 -> "Thursday"
            5 -> "Friday"
            6 -> "Saturday"
            7 -> "Sunday"
            else -> "Invalid day"
        }
    }
    
  2. Lambda Expressions and Higher-Order Functions

    val numbers = listOf(1, 2, 3, 4, 5)
    val doubled = numbers.map { it * 2 }  // Lambda expression
    
  3. Destructuring Declarations

    data class Person(val name: String, val age: Int)
    val person = Person("Alice", 30)
    val (name, age) = person  // Destructuring declaration
    
  4. Elvis Operator

    val nullableString: String? = null
    val nonNullableString: String = nullableString ?: "Default Value"  // Elvis operator
    
  5. String Templates

    val greeting = "Hello, $name!"
    
  6. Smart Casts

    fun getStringLength(obj: Any): Int? {
        if (obj is String) {
            return obj.length  // Smart cast
        }
        return null
    }
    
  7. Single-Expression Functions

    fun square(x: Int) = x * x
    
  8. Default Parameter Values

    fun greet(name: String = "Guest") {
        println("Hello, $name!")
    }
    
  9. Extension Functions

    fun String.isPalindrome(): Boolean {
        return this == this.reversed()
    }
    
    val word = "madam"
    val isPalindrome = word.isPalindrome()
    
  10. Operator Overloading

    data class Point(val x: Int, val y: Int) {
        operator fun plus(other: Point) = Point(x + other.x, y + other.y)
    }
    
    val point1 = Point(2, 3)
    val point2 = Point(4, 5)
    val point3 = point1 + point2
    
  11. Printing All Results

    fun main() {
        println(getDayOfWeek(3))  // Output: Wednesday
        println(doubled)  // Output: [2, 4, 6, 8, 10]
        println("Name: $name, Age: $age")  // Output: Name: Alice, Age: 30
        println(nonNullableString)  // Output: Default Value
        println(greeting)  // Output: Hello, Alice!
        println(getStringLength("Kotlin"))  // Output: 6
        println(square(4))  // Output: 16
        greet()  // Output: Hello, Guest!
        println(isPalindrome)  // Output: true
        println(point3)  // Output: Point(x=6, y=8)
    }
    
    main()
    

let

The let function is used to invoke a lambda function on the object it is called on. It returns the result of the lambda expression.

val result = "Hello".let {
    println(it)
    it.length
}
println(result) // Output: 5

also

The also function is similar to let, but it returns the original object instead of the result of the lambda expression. It’s often used for side effects, such as logging or validation.

val result = "Hello".also {
    println(it)
}.toUpperCase()
println(result) // Output: HELLO

run

The run function is used to execute a block of code and return its result. It can be called on an object and within a scope.

val result = "Hello".run {
    println(this)
    this.length
}
println(result) // Output: 5

with

The with function is a non-extension function that can be used to call multiple methods on the same object without repeating the object’s name.

val result = with("Hello") {
    println(this)
    this.length
}
println(result) // Output: 5

apply

The apply function is used for configuring an object. It runs a block of code on the object and returns the object itself.

val result = StringBuilder().apply {
    append("Hello")
    append(" World")
}
println(result.toString()) // Output: Hello World

takeIf

The takeIf function returns the object if it satisfies the given predicate; otherwise, it returns null.

val result = "Hello".takeIf {
    it.length > 3
}
println(result) // Output: Hello

takeUnless

The takeUnless function returns the object if it does not satisfy the given predicate; otherwise, it returns null.

val result = "Hello".takeUnless {
    it.length > 5
}
println(result) // Output: Hello
  • 15
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值