当前位置: 首页 > news >正文

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: Wednesdayprintln(doubled)  // Output: [2, 4, 6, 8, 10]println("Name: $name, Age: $age")  // Output: Name: Alice, Age: 30println(nonNullableString)  // Output: Default Valueprintln(greeting)  // Output: Hello, Alice!println(getStringLength("Kotlin"))  // Output: 6println(square(4))  // Output: 16greet()  // Output: Hello, Guest!println(isPalindrome)  // Output: trueprintln(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
http://www.lryc.cn/news/370919.html

相关文章:

  • .NET MAUI Sqlite数据库操作(一)
  • SQL 窗口函数
  • staruml怎么合并多个Project工程文件
  • 设计模式——外观模式
  • 开源-Docker部署Cook菜谱工具
  • 使用PHP对接企业微信审批接口的问题与解决办法(二)
  • RK3288 android7.1 实现ota升级时清除用户数据
  • okHttp的https请求忽略ssl证书认证
  • 在Java中使用Spring Boot设置全局的BusinessException
  • Java 异常处理 -- Java 语言的异常、异常链与断言
  • Spring Cloud Nacos 详解:服务注册与发现及配置管理平台
  • java多线程临界区介绍
  • 基于JSP的超市管理系统
  • 一文讲清:生产报工系统的功能、报价以及如何选择
  • blender bpy将顶点颜色转换为UV纹理vertex color to texture
  • Flink Sql:四种Join方式详解(基于flink1.15官方文档)
  • (delphi11最新学习资料) Object Pascal 学习笔记---第14章泛型第3节(泛型约束)
  • C语言详解(预编译)
  • 解决el-table表格拖拽后,只改变了数据,表头没变的问题
  • 简单塔防小游戏
  • 高考之后第一张大流量卡应该怎么选?
  • 如何从微软官方下载Edge浏览器的完整离线安装包
  • git 常用的命令
  • 【StableDiffusion】Embedding 底层原理,Prompt Embedding,嵌入向量
  • 计算机网络(2) 网络层:IP服务模型
  • 新人学习笔记之(初识C语言)
  • Unity EasyRoads3D插件使用
  • Redis 地理散列GeoHash
  • vim 显示行号
  • C++:调整数组顺序使奇数位于偶数前面【面试】