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:提升代码质量与开发效率的秘诀 的相关文章

  • 多输出堆叠回归器

    一次性问题 我正在尝试构建一个多输入堆叠回归器 添加到 sklearn 0 22 据我了解 我必须结合StackingRegressor and MultiOutputRegressor 经过多次尝试 这似乎是正确的顺序 import nu
  • 嵌套列表的重叠会产生不必要的间隙

    我有一个包含三个列表的嵌套 这些列表由 for 循环填充 并且填充由 if 条件控制 第一次迭代后 它可能类似于以下示例 a 1 2 0 0 0 0 0 0 4 5 0 0 0 0 0 0 6 7 根据条件 它们不重叠 在第二次迭代之后 新
  • 如何从Python中的函数返回多个值? [复制]

    这个问题在这里已经有答案了 如何从Python中的函数返回多个变量 您可以用逗号分隔要返回的值 def get name you code return first name last name 逗号表示它是一个元组 因此您可以用括号将值括
  • 使用主题交换运行多个 Celery 任务

    我正在用 Celery 替换一些自制代码 但很难复制当前的行为 我期望的行为如下 创建新用户时 应向tasks与交换user created路由键 该消息应该触发两个 Celery 任务 即send user activate email
  • 在 Django Admin 中调整字段大小

    在管理上添加或编辑条目时 Django 倾向于填充水平空间 但在某些情况下 当编辑 8 个字符宽的日期字段或 6 或 8 个字符的 CharField 时 这确实是一种空间浪费 字符宽 然后编辑框最多可容纳 15 或 20 个字符 我如何告
  • 为什么 web2py 在启动时崩溃?

    我正在尝试让 web2py 在 Ubuntu 机器上运行 所有文档似乎都表明要在 nix 系统上运行它 您需要下载源代码并执行以下操作 蟒蛇 web2py py 我抓住了source http www web2py com examples
  • Tensorboard SyntaxError:语法无效

    当我尝试制作张量板时 出现语法错误 尽管开源代码我还是无法理解 我尝试搜索张量板的代码 但不清楚 即使我不擅长Python 我这样写路径C Users jh902 Documents logs因为我正在使用 Windows 10 但我不确定
  • 矩形函数的数值傅里叶变换

    本文的目的是通过一个众所周知的分析傅里叶变换示例来正确理解 Python 或 Matlab 上的数值傅里叶变换 为此 我选择矩形函数 这里报告了它的解析表达式及其傅立叶变换https en wikipedia org wiki Rectan
  • Python 内置的 super() 是否违反了 DRY?

    显然这是有原因的 但我没有足够的经验来认识到这一点 这是Python中给出的例子docs http docs python org 2 library functions html super class C B def method se
  • 使用 Python Oauthlib 通过服务帐户验证 Google API

    我不想使用适用于 Python 的 Google API 客户端库 但仍想使用 Python 访问 Google APIOauthlib https github com idan oauthlib 创建服务帐户后谷歌开发者控制台 http
  • python的shutil.move()在linux上是原子的吗?

    我想知道python的shutil move在linux上是否是原子的 如果源文件和目标文件位于两个不同的分区上 行为是否不同 或者与它们存在于同一分区上时的行为相同吗 我更关心的是如果源文件和目标文件位于同一分区上 shutil move
  • Django 视图中的“请求”是什么

    在 Django 第一个应用程序的 Django 教程中 我们有 from django http import HttpResponse def index request return HttpResponse Hello world
  • 如何将 ascii 值列表转换为 python 中的字符串?

    我在 Python 程序中有一个列表 其中包含一系列数字 这些数字本身就是 ASCII 值 如何将其转换为可以在屏幕上回显的 常规 字符串 您可能正在寻找 chr gt gt gt L 104 101 108 108 111 44 32 1
  • Python - 如何确定解析的 XML 元素的层次结构级别?

    我正在尝试使用 Python 解析 XML 文件中具有特定标记的元素并生成输出 excel 文档 该文档将包含元素并保留其层次结构 我的问题是我无法弄清楚每个元素 解析器在其上迭代 的嵌套深度 XML 示例摘录 3 个元素 它们可以任意嵌套
  • 带有 LSTM 的 GridSearchCV/RandomizedSearchCV

    我一直在尝试通过 RandomizedSearchCV 调整 LSTM 的超参数 我的代码如下 X train X train reshape X train shape 0 1 X train shape 1 X test X test
  • 根据 Pandas 中的列表选择数据框行的子集

    我有一个数据框df1并列出x In 22 import pandas as pd In 23 df1 pd DataFrame C range 5 B range 10 20 2 A list abcde In 24 df1 Out 24
  • 如何在 Flask 中的视图函数/会话之间传递复杂对象

    我正在编写一个 Web 应用程序 当 且仅当 用户登录时 该应用程序从第三方服务器接收大量数据 这些数据被解析为自定义对象并存储在list 现在 用户在应用程序中使用这些数据 调用不同的视图 例如发送不同的请求 我不确定什么是最好的模式在视
  • 将索引与值交换的最快方法

    考虑pd Series s s pd Series list abcdefghij list ABCDEFGHIJ s A a B b C c D d E e F f G g H h I i J j dtype object 交换索引和值并
  • pytest找不到模块[重复]

    这个问题在这里已经有答案了 我正在关注pytest 良好实践 https docs pytest org en latest explanation goodpractices html test discovery或者至少我认为我是 但是
  • 如何将Python3设置为Mac上的默认Python版本?

    有没有办法将 Python 3 8 3 设置为 macOS Catalina 版本 10 15 2 上的默认 Python 版本 我已经完成的步骤 看看它安装在哪里 ls l usr local bin python 我得到的输出是这样的

随机推荐

  • 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