some idioms
1.1. Create DTOs (POJOs/POCOs)
DTO
: Data transfer object, its interpretation isData Transfer Object
;
POJO
: Simplejava
object , which is actually ordinaryJavaBean
. Its explanation isPlain Old Java Object
;
POCO
:POJO
The meaning of the same is the same, the only difference is the language used. Therefore, its interpretation isPlain Old C# Object
.
data class Customer(val name: String, val email: String)
A Customer class is provided with the following functions:
- getters for all properties (and setters if var properties)
- equals()
- hashCode()
- toString()
- copy()
- component1(), component2(),... of all properties (explained in the Data classes section)
1.2, the default value of function parameters
fun foo(a: Int = 0, b: String = "") { ... }
1.3, filter list list
val positives = list.filter { x -> x > 0 }
or is relatively simpler to write:
val positives = list.filter { it > 0 }
Note: it
what is it? Additional explanation will be given later. It is probably known here that it is an object representing a collection instance.
1.4. String interpolation
println("Name $name") // 字符串模板
1.5. Instance Check
// 类型检查,自动转换类型
when (x) {
is Foo -> ...
is Bar -> ...
else -> ...
}
1.6. Traverse the map/list (in the form of key-value pairs)
for ((k, v) in map) {
println("$k -> $v")
}
k
,v
can be called anything.
1.7. Use interval
for (i in 1..100) { ... } // closed range: includes 100
for (i in 1 until 100) { ... } // half-open range: does not include 100
for (x in 2..10 step 2) { ... }
for (x in 10 downTo 1) { ... }
if (x in 1..10) { ... }
1.8, read-only list
val list = listOf("a", "b", "c")
1.9, read-only mapping
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
1.10, access mapping
println(map["key"])
map["key"] = value
1.11, Lazy property
val p: String by lazy {
// compute the string
}
1.12, extension function
fun String.spaceToCamelCase() { ... }
"Convert this to camelcase".spaceToCamelCase()
1.13. Create a singleton
object Resource {
val name = "Name"
}
1.14, if non-space write
val files = File("Test").listFiles()
println(files?.size)
1.15, if non-empty and else shorthand
al files = File("Test").listFiles()
println(files?.size ?: "empty")
1.16, if empty execution statement
val values = ...
val email = values["email"] ?: throw IllegalStateException("Email is missing!")
1.17. Get the first data of a possibly empty collection
val emails = ... // might be empty
val mainEmail = emails.firstOrNull() ?: ""
1.18, if non-empty execution
val value = ...
value?.let {
... // execute this block if not null
}
1.19, if non-null, map null value
val value = ...
val mapped = value?.let { transformValue(it) } ?: defaultValueIfValueIsNull
1.20, when statement return value
fun transform(color: String): Int {
return when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
}
1.21, try/catch expressions
fun test() {
val result = try {
count()
} catch (e: ArithmeticException) {
throw IllegalStateException(e)
}
// Working with result
}
1.22, if expression
fun foo(param: Int) {
val result = if (param == 1) {
"one"
} else if (param == 2) {
"two"
} else {
"three"
}
}
1.23. Method builder style usage that returns Unit type
fun arrayOfMinusOnes(size: Int): IntArray {
return IntArray(size).apply { fill(-1) }
}
1.24, single expression function
fun theAnswer() = 42
Equivalent to
fun theAnswer(): Int {
return 42
}
This can also be combined effectively with other idioms to simplify code. Such as: with when expression:
fun transform(color: String): Int = when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
1.25. Calling multiple methods in 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()
}
1.26, Java7 resources
val stream = Files.newInputStream(Paths.get("/some/file.txt"))
stream.buffered().reader().use { reader ->
println(reader.readText())
}
1.27. Convenience forms for generic functions that require 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)
1.27. Consume nullable Boolean
val b: Boolean? = ...
if (b == true) {
...
} else {
// `b` is false or null
}