kotlin编码格式
Kotlin is a cross-platform, statically typed, general-purpose programming language with type inference. Kotlin is designed to interoperate fully with Java, and the JVM version of Kotlin’s standard library depends on the Java Class Library, but type inference allows its syntax to be more concise. I have used this language for a while now and below I’ll show some tips for beginners.
Kotlin是具有类型推断功能的跨平台,静态类型的通用编程语言。 Kotlin旨在与Java完全互操作,并且Kotlin标准库的JVM版本取决于Java类库,但是类型推断使它的语法更加简洁。 我已经使用这种语言一段时间了,下面我将向初学者展示一些技巧。
应用 (Apply)
A common use case for apply is to make additional configurations on a recently created object:
apply一个常见用例是在最近创建的对象上进行其他配置:
val turtle = Turtle().apply{Name = "Joe"Age = 50
}
Notice how when you use apply, it will return the object you modified back to you.
请注意,当您使用apply ,它将如何将您修改过的对象返回给您。
用 (With)
A common use case for with is to call multiple methods on the same object. In that case, this:
with常见用例是在同一个对象上调用多个方法。 在这种情况下,这是:
file.load()
file.modify()
file.modifyMore()
file.save()
will become this:
会变成这样:
with(file){load()modify()modifyMore()save()
}
Keep in mind that the above returns the result of the last expression.
请记住,以上返回最后一个表达式的结果。
方法返回使用= (Method Returns Using =)
If you have a method that contains only a single return statement, you can omit the return type, return keyword, and braces, and replace them all with =. In that case, this:
如果您有一个仅包含单个return语句的方法,则可以省略return类型,return关键字和花括号,并将其全部替换为= 。 在这种情况下,这是:
fun sum(val a: Int, val b: Int): Int {return a+b
}
becomes this:
变成这个:
fun sum(val a: Int, val b: Int) = a + b
范围 (Ranges)
Ranges are useful for cycle conditions, as shown here:
范围对于循环条件很有用,如下所示:
for (i in 1..5) print(i) // results in "12345"
However, this doesn’t work in reverse:
但是,这并非相反:
for (i in 5..1) print(i) // prints nothing
Instead, here is the proper backward iteration:
相反,这是适当的向后迭代:
for (i in 5 downTo 1) print(i) // results in "54321"
You can also use until, like so:
您还可以使用until ,如下所示:
for (i in 0 until 5) { // results in "01234"println(i)
}
This is frequently used to iterate through collections:
这通常用于遍历集合:
for(i in 0 until list.size()){println(i)
}
什么时候 (When)
When is a more powerful version of Java’s switch, and it combines nicely with ranges, as shown here:
Java的switch一个更强大的版本When ,它与范围很好地结合在一起,如下所示:
when (x) {in 0 until 5 -> println("x is in range")is 10 -> println("the special case, when x is 10")else -> println("none of the above")
}
It can be also used as a return statement, but you need to either specify all possible cases (make it exhaustive) or include else:
它也可以用作return语句,但是您需要指定所有可能的情况(使其详尽)或包括else :
enum class Theme {DEFAULT,DARK,XMAS
}fun getThemeLogo() = when (theme) {DEFAULT -> getDefaultLogo()DARK -> getDarkLogo()XMAS -> getXmasLogo()
}fun getThemeLogoExcludingPromos() = when (theme) {DEFAULT -> getDefaultLogo()DARK -> getDarkLogo()else -> getDefaultLogo()
}
Additionally, you can use when as an expression, but it doesn’t need to be exhaustive in this case:
另外,您可以将when用作表达式,但是在这种情况下,它不需要穷举:
fun showAnimations() {when (theme) {DEFAULT -> showAnimation()XMAS -> showXmasAnimation()
}
}
Finally, when can be used along with smart casts:
最后, when可以与智能投射一起使用:
when(file) {is Directory -> processDirectory()is Document -> processDocument()
}
资料类别 (Data Classes)
Data classes are classes that have the specific purpose of holding data:
数据类是具有保存数据的特定目的的类:
data class Turtle(val name: String, val age: Int)
The data class will have the following function out of the box:
数据类具有以下功能:
toString of the form "Turtle(name=Joe, age=50)" equals() and hashCode() copy()
"Turtle(name=Joe, age=50)"形式的toString equals()和hashCode() copy()
It will also become a subject for destructuring declarations:
它也将成为破坏声明的主题:
val turtleJoe = Turtle("Joe", 50)val (name, age) = turtleJoeprintln(name)println(age)
静态字段和常量 (Static Fields and Constants)
Static fields are commonly used in Java, but they are a bit tricky in Kotlin. The closest thing to the concept of static fields in Kotlin is a companion object declared inside the class.
静态字段通常在Java中使用,但是在Kotlin中它们有些棘手。 与Kotlin中的静态字段概念最接近的是在类内部声明的伴随对象。
Here is how you can declare a static constant:
这是声明静态常量的方法:
class Theme {companion object { const val THEME_KEY = "a_theme_key" }
}
空安全 (Null Safety)
Kotlin provides tools to help you prevent the most common type of runtime exceptions: NullPointerExceptions (NPEs).
Kotlin提供了一些工具来帮助您防止最常见的运行时异常类型: NullPointerException (NPE)。
To do this, you first need to explicitly specify that you want some field/variable to hold null:
为此,您首先需要明确指定要让某些字段/变量保持null :
var text: String // can't hold null
text = null // compilation errorvar textOrNull: String? // can hold null (specified by adding ?)
textOrNull = null // compiles just fine
If you use the second version, Kotlin will expect a null handling logic, and there are tools to simplify that as well.
如果您使用第二个版本,则Kotlin将期望使用null处理逻辑,并且还有一些工具可以简化该逻辑。
Safe calls ?. to perform an action on a nullable object:
安全电话?. 对可为空的对象执行操作:
var textOrNull: String?
textOrNull?.length // will return length or null
The Elvis operator ?: specifies actions to take in case of a null:
Elvis运算符?:指定为null要采取的行动:
textOrNull?.length ?: 0 // will return length or 0 in case of a null
There is also the let operator, which can be used if you need a code block to execute only when something isn’t null:
还有一个let运算符,如果仅当某些内容不为null时需要执行代码块时才可以使用它:
currentTheme?.let {applyTheme(theme)// we are certain it is not null heresendAnalyticsThemeEvent(theme)
}
Finally, there is !!, which converts any value to a non-null type and throws an exception if the value is null. This operator may look like an easy escape for null handling chores, but it should be avoided at all costs since Kotlin does so much to help to get rid of NPEs.
最后,有!! ,它将任何值转换为非null类型,并且如果该值为null则抛出异常。 该操作员看起来像是空操作琐事的轻松逃脱,但是应尽一切可能避免这种操作,因为Kotlin竭尽全力帮助摆脱NPE。
There is much more to Kotlin, but for the sake of simplicity, this is a good starting point. Hopefully, it will be a useful guide about frequently used Kotlin practices to help get you up and running.
Kotlin还有很多东西,但是为了简单起见,这是一个很好的起点。 希望它对经常使用Kotlin的实践有用,对您有所帮助。
翻译自: https://levelup.gitconnected.com/tips-for-coding-with-kotlin-e90880ff5dbc
kotlin编码格式


所有评论(0)