Kotlin Idioms:提升代码质量与开发效率的秘诀

2023-12-05

Create DTOs (POJOs/POCOs)

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

provides a Customer class with the following functionality:

  • getters (and setters in case of var s) for all properties
  • equals()
  • hashCode()
  • toString()
  • copy()
  • component1() , component2() , …, for all properties (see Data classes )

Default values for function parameters

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

Filter a list

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

Or alternatively, even shorter:

val positives = list.filter { it > 0 }

Learn the difference between Java and Kotlin filtering .

Check the presence of an element in a collection

if ("john@example.com" in emailsList) { ... }

if ("jane@example.com" !in emailsList) { ... }

String interpolation

println("Name $name")

Learn the difference between Java and Kotlin string concatenation .

Instance checks

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

Read-only list

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

Read-only map

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

Access a map entry

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

Traverse a map or a list of pairs

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

k and v can be any convenient names, such as name and age .

Iterate over a range

for (i in 1..100) { ... }  // closed-ended range: includes 100
for (i in 1..<100) { ... } // open-ended range: does not include 100
for (x in 2..10 step 2) { ... }
for (x in 10 downTo 1) { ... }
(1..10).forEach { ... }

Lazy property

val p: String by lazy { // the value is computed only on first access
    // compute the string
}

Extension functions

fun String.spaceToCamelCase() { ... }

"Convert this to camelcase".spaceToCamelCase()

Create a singleton

object Resource {
    val name = "Name"
}

Instantiate an abstract class

abstract class MyAbstractClass {
    abstract fun doSomething()
    abstract fun sleep()
}

fun main() {
    val myObject = object : MyAbstractClass() {
        override fun doSomething() {
            // ...
        }

        override fun sleep() { // ...
        }
    }
    myObject.doSomething()
}

If-not-null shorthand

val files = File("Test").listFiles()

println(files?.size) // size is printed if files is not null

If-not-null-else shorthand

val files = File("Test").listFiles()

// For simple fallback values:
println(files?.size ?: "empty") // if files is null, this prints "empty"

// To calculate a more complicated fallback value in a code block, use `run`
val filesSize = files?.size ?: run { 
    val someSize = getSomeSize()
    someSize * 2
}
println(filesSize)

Execute a statement if null

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

Get first item of a possibly empty collection

val emails = ... // might be empty
val mainEmail = emails.firstOrNull() ?: ""

Learn the difference between Java and Kotlin first item getting .

Execute if not null

val value = ...

value?.let {
    ... // execute this block if not null
}

Map nullable value if not null

val value = ...

val mapped = value?.let { transformValue(it) } ?: defaultValue 
// defaultValue is returned if the value or the transform result is null.

Return on when statement

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

try-catch expression

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

    // Working with result
}

if expression

val y = if (x == 1) {
    "one"
} else if (x == 2) {
    "two"
} else {
    "other"
}

Builder-style usage of methods that return Unit

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

Single-expression functions

fun theAnswer() = 42

This is equivalent to

fun theAnswer(): Int {
    return 42
}

This can be effectively combined with other idioms, leading to shorter code. For example, with the when expression:

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

Call multiple methods on an object instance (with)

class Turtle {
    fun penDown()
    fun penUp()
    fun turn(degrees: Double)
    fun forward(pixels: Double)
}

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

Configure properties of an object (apply)

val myRectangle = Rectangle().apply {
    length = 4
    breadth = 5
    color = 0xFAFAFA
}

This is useful for configuring properties that aren’t present in the object constructor.

Java 7’s try-with-resources

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

Generic function that requires the generic type information

//  public final class Gson {
//     ...
//     public <T> T fromJson(JsonElement json, Class<T> classOfT) throws JsonSyntaxException {
//     ...

inline fun <reified T: Any> Gson.fromJson(json: JsonElement): T = this.fromJson(json, T::class.java)

Swap two variables

var a = 1
var b = 2
a = b.also { b = a }

Mark code as incomplete (TODO)

Kotlin’s standard library has a TODO() function that will always throw a NotImplementedError .
Its return type is Nothing so it can be used regardless of expected type.
There’s also an overload that accepts a reason parameter:

fun calcTaxes(): BigDecimal = TODO("Waiting for feedback from accounting")

IntelliJ IDEA’s kotlin plugin understands the semantics of TODO() and automatically adds a code pointer in the TODO tool window.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Kotlin Idioms:提升代码质量与开发效率的秘诀 的相关文章

  • Virtualenv 在 OS X Yosemite 上失败并出现 OSError

    我最近更新到 OSX Yosemite 现在无法使用virtualenv pip 每当我执行 virtualenv env 它抛出一个 OSError Command Users administrator ux env bin pytho
  • 多处理中的动态池大小?

    有没有办法动态调整multiprocessing Pool尺寸 我正在编写一个简单的服务器进程 它会产生工作人员来处理新任务 使用multiprocessing Process对于这种情况可能更适合 因为工作人员的数量不应该是固定的 但我需
  • 如何返回 cost, grad 作为 scipy 的 fmin_cg 函数的元组

    我怎样才能使 scipy 的fmin cg使用一个返回的函数cost and gradient作为元组 问题是有f对于成本和fprime对于梯度 我可能必须执行两次操作 非常昂贵 grad and cost被计算 此外 在它们之间共享变量可
  • Chromium 中的 MP4 编解码器支持

    我们已将 Chromium 嵌入式框架集成到我们的 Windows 游戏中 以允许我们从应用程序内渲染网页 并且一切正常 除了 MP4 视频 据我所知 由于许可问题 Chromium 不包含此编解码器 但任何人都可以提供有关我们如何添加支持
  • 使用python从gst管道抓取帧到opencv

    我在用着OpenCV http opencv org 和GStreamer0 10 我使用此管道通过自定义套接字通过 UDP 接收 MPEG ts 数据包sockfd由 python 提供并显示它xvimagesink 而且效果很好 以下命
  • Python Tkinter 模块不显示输出

    我正在尝试学习 Python 并尝试使用 Python 中的 GUI 并遇到了这个 Tkinter 模块 我的代码运行 但运行时窗口没有出现 我的代码如下 from Tkinter import to create a root windo
  • Python HMAC:类型错误:字符映射必须返回整数、None 或 unicode

    我在使用 HMAC 时遇到了一个小问题 运行这段代码时 signature hmac new key secret key msg string to sign digestmod sha1 我收到一个奇怪的错误 File usr loca
  • 运行 Python 单元测试,以便成功时不打印任何内容,失败时仅打印 AssertionError()

    我有一个标准单元测试格式的测试模块 class my test unittest TestCase def test 1 self tests def test 2 self tests etc 我的公司有一个专有的测试工具 它将作为命令行
  • 如何停止执行的 Jar 文件

    这感觉像是一个愚蠢的问题 但我似乎无法弄清楚 当我在 Windows 上运行 jar 文件时 它不会出现在任务管理器进程中 我怎样才能终止它 我已经尝试过 TASKKILL 但它对我也不起作用 On Linux ps ef grep jav
  • python中basestring和types.StringType之间的区别?

    有什么区别 isinstance foo types StringType and isinstance foo basestring 对于Python2 basestring是两者的基类str and unicode while type
  • 从 Flask 运行 NPM 构建

    我有一个 React 前端 我想在与我的 python 后端 API 相同的源上提供服务 我正在尝试使用 Flask 来实现此目的 但我遇到了 Flask 找不到我的静态文件的问题 我的前端构建是用生成的npm run build in s
  • 给定一个排序数组,就地删除重复项,使每个元素仅出现一次并返回新长度

    完整的问题 我开始在线学习 python 但对这个标记为简单的问题有疑问 给定一个排序数组 就地删除重复项 使得每个 元素只出现一次并返回新的长度 不分配 另一个数组的额外空间 您必须通过修改输入来完成此操作 数组就地 具有 O 1 额外内
  • 使用 Python 将连续日期分组在一起

    Given dates datetime 2014 10 11 datetime 2014 10 1 datetime 2014 10 2 datetime 2014 10 3 datetime 2014 10 5 datetime 201
  • Docker Desktop 不会切换到 Windows 容器(在 Windows 10 上)

    我有 Windows 10 专业版 版本 21H1 BIOS 中已启用虚拟化 Hyper V 正在运行 我已经安装了适用于 Windows 的 Docker Desktop 如上所述here https docs docker com de
  • 无法通过 Python 子进程进行 SSH

    我需要通过堡垒 ssh 进入机器 因此 该命令相当长 ssh i
  • 如何在亚马逊 EC2 上调试 python 网站?

    我是网络开发新手 这可能是一个愚蠢的问题 但我找不到可以帮助我的确切答案或教程 我工作的公司的网站 用 python django 构建 托管在亚马逊 EC2 上 我想知道从哪里开始调试这个生产站点并检查存储在那里的日志和数据库 我有帐户信
  • Django 管理器链接

    我想知道是否有可能 如果可以的话 如何 将多个管理器链接在一起以生成受两个单独管理器影响的查询集 我将解释我正在研究的具体示例 我有多个抽象模型类 用于为其他模型提供小型的特定功能 其中两个模型是DeleteMixin 和GlobalMix
  • pandas 中数据帧中的随机/洗牌行

    我目前正在尝试找到一种方法来按行随机化数据框中的项目 我在 pandas 中按列洗牌 排列找到了这个线程 在 pandas 中对 DataFrame 进行改组 排列 https stackoverflow com questions 157
  • 如何使用 python 定位和读取 Data Matrix 代码

    我正在尝试读取微管底部的数据矩阵条形码 我试过libdmtx http libdmtx sourceforge net 它有 python 绑定 当矩阵的点是方形时工作得相当好 但当矩阵的点是圆形时工作得更糟 如下所示 另一个复杂问题是在某
  • IndexError - 具有匀称形状的笛卡尔 PolygonPatch

    我曾经使用 shapely 制作一个圆圈并将其绘制在之前填充的图上 这曾经工作得很好 最近 我收到索引错误 我将代码分解为最简单的操作 但它甚至无法执行最简单的循环 import descartes import shapely geome

随机推荐

  • Linux 编译安装colmap

    COLMAP可以作为独立的app 通过命令行或者图形交互界面使用 也可以作为一个库被包含到其他源代码中 这里记录一下编译安装colmap的过程 首先需要安装好CUDA CUDA具体安装过程这里就不赘述了 在GitHub上下载源代码 我这里就
  • VIM使用快捷键快速移动到某个位置

    光标移动到行首 行首没有空格 光标移动到行首 行首有空格 数字0 光标移动到行尾 移动到指定行 7G 数字加一个大G 光标移动到文件开始 gg 两个小g 光标移动到文件末尾 G 一个大G 窗口向上滚动一行 Ctrl e scroll up
  • mapbox实现点选要素

    成果图 核心代码 核心逻辑就是指定一个唯一的高亮要素对象 全图监听点击事件 通过queryRenderedFeatures鼠标点拿到要素的id 然后将要素的状态改为选中 这样选中的要素的样式就会改为我们设置好的选中的样式 记住这个高亮对象
  • Gazebo 中为地面和车轮添加摩擦属性

    Gazebo 中为地面和车轮添加摩擦属性 Link friction properties not applied from URDF to Gazebo SDFormat Specification Adding friction to
  • 无尘车间等级划分标准

    在制造业 医药行业 食品行业等领域中 无尘车间是一个非常重要的组成部分 无尘车间能够提供清洁 高度控制的环境 有利于产品质量的提高和生产过程的优化 SICOLAB喜格 将详细介绍无尘车间的等级划分标准 包括其定义 方法和重要性 一 无尘车间
  • Matlab中文注释在Linux中乱码解决

    Linux for Matlab中文注释乱码 Linux for Matlab中文注释乱码 亲测有效 中文注释乱码的原因是windows下的m文件采用的是gbk编码 只要将所有的m文件转成 utf8文件 显示就正常了 查看支持的语言 enc
  • Linux系列-1 Linux启动流程——init与systemd进程

    背景 最近对所有项目完成了一个切换 服务管理方式由 init gt systemd 对相关知识进行总结一下 1 启动流程 服务器的整体启动流程如下图所示 POST 计算机通电后进行POST Power On Self Test 加电自检 检
  • C#8.0本质论第十六章--使用查询表达式的LINQ

    C 8 0本质论第十六章 使用查询表达式的LINQ 像SQL这样的专业查询语言虽然容易阅读和理解 但又缺乏C 语言的完整功能 这正是C 语言设计者在C 3 0中添加 查询表达式 语法的原因 本章大部分都类似于SQL 一般不会使用到 在用到的
  • python能用来做什么?这3大主要用途你一定要知道!(实用)_python能做什么

    导读 如果你想学Python 或者你刚开始学习Python 那么你可能会问 我能用Python做什么 这个问题不好回答 因为Python有很多用途 但是随着时间 我发现有Python主要有以下三大主要应用 Web开发 数据科学 包括机器学习
  • 无尘车间装修要符合哪些要求

    无尘车间装修是工业生产中非常重要的一环 它能够提供高度洁净的生产环境 保证产品在生产过程中的质量和安全性 因此 无尘车间的装修设计必须符合一系列要求 以确保其使用效果和性能达到最佳状态 SICOLAB喜格 将详细介绍无尘车间装修要符合哪些要
  • 学会Python怎么找兼职?

    当今收入低于5000的人至少占到40 完全不够养活一家人 而且很多小伙伴其实空余时间比较多 特别是大学生 零花钱又不够花 都想靠业余时间找点轻松的活增加收入 但是缺没门路 为此结合我多年编程开发经验 总结了几种用Python赚外快的方法 最
  • Mybatis简介

    1 MyBatis历史 MyBatis最初是Apache的一个开源项目iBatis 2010年6月这个项目由Apache Software Foundation迁移到了Google Code 随着开发团队转投Google Code旗下 iB
  • 光纤和光模块的那点事儿

    你们好 我的网工朋友 应该不少朋友在工作中会遇到光纤传输布线的活吧 不得不说 会遇上的问题还挺多 比如说 光纤收发器怎么接上不亮 光纤收发器和交换机插光模块能不能搭配使用 带光口的球机可以和交换机搭配使用吗 这些你都懂多少 这篇文章 和你聊
  • Python系列:如何提高python程序代码的健壮性

    概要 在编程的时候 我们难免会遇到一些不可靠的情况 比如网络请求失败 数据库连接超时等等 这些不确定性会让我们的程序容易出现各种错误和异常 那么如何来增加程序的容错性和健壮性呢 可能大多数人会想到使用try except来进行异常捕捉进行失
  • 牙髓干细胞实验室建设

    科技的不断进步 干细胞研究已经逐渐成为生物医学领域的研究热点 其中 牙髓干细胞因其独特的生物特性和巨大的应用潜力 受到了越来越多科学家的关注 SICOLAB喜格 为了满足这一研究需求 牙髓干细胞实验室的建设显得尤为重要 一 牙髓干细胞实验室
  • 压缩docker在主机的虚拟磁盘容量

    我们在windows里使用docker时会发现 即使我们已经删除了无用的镜像和容器 主机里挂在docker虚拟磁盘的那个盘 可用空间也没有增加 这是因为虚拟磁盘不会自动缩小 这里我分享一个可用的解决方案 1 先通过docker回收空间 do
  • 使用Draw.io制作泳道图

    使用Draw io制作泳道图 一 横向泳道图 1 有标题泳道图 2 无标题泳道图 3 横纵向扩展泳道 二 纵向泳道图
  • 大火的占用网络究竟如何落地?国内首个面向工业级占用网络全栈教程!

    2022年9月的Tesla AI Day上 一种称之为Occupancy Network的占用模型突然出现到大家的视野中 轻语义重几何 更好地辅助自动驾驶系统感知Driverable space 自动驾驶在动静态障碍物感知领域的发展大概分为
  • vscode调试mit6s081Lab

    环境 mit6 s081的实验环境 gdb multiarch 用于gdb调试 vscode调试实质上就是提供个图形化页面 底层还是这个 安装 gdb multiarch sudo apt get install gdb multiarch
  • Kotlin Idioms:提升代码质量与开发效率的秘诀

    Create DTOs POJOs POCOs data class Customer val name String val email String provides a Customer class with the followin