Author: Chen Tong, 2018.9.28
#### Kotlin simulation runner try.kotlinlang.org/
#### idiom
- The function definitions
Fun sum(a: Int, b: Int): Int {returnA + b} // No return value funprintSum(a: Int, b: Int) {
println("sum of $a and $b is ${a + b}")}Copy the code
- Define variables
Var x = 1; var x = 1Copy the code
- String template $
var a = 1
val s1 = "a is $a"
Copy the code
- Conditional expressions are written uniformly
if (a > b) {
return a
} else {
return b
}
Copy the code
- Null verifies null
When the value of a variable can be null, it must be added after the type at the declaration. To indicate that the reference is nullable
val str: String ? = nullCopy the code
- Data type detection
fun getStringLength(obj: Any): Int? {if(obj is String){
return obj.length
}
return null
}
Copy the code
- Use the for loop
1, similar to Java enhanced for loop
Val items = listOf("apple"."banana"."kiwifruit")
for (item in items) {
println(item)
}
Copy the code
or
val items = listOf("apple"."banana"."kiwifruit")
for (index in items.indices)
{
println("item at $index is ${items[index]}")}Copy the code
Advantage of the while loop: Precise control over index
val items = listOf("apple"."banana"."kiwifruit")
var index = 0
while (index < items.size) {
println("item at $index is ${items[index]}")
index++
}
Copy the code
The interval method
// ascending val n = 11for (x in1.. n step 2) {print(x)
}
Copy the code
or
/ / descendingfor (x in 9 downTo 0 step 3)
{
print(x)
}
Copy the code
- Interval detection
1. Whether it is within a certain range
val x = 10
val y = 9
if (x in1.. y+1) { println("fits in range")}Copy the code
- When expression (instead of switch)
when (x) {
1 -> print("x == 1"2 - >)print("x == 2")
else -> { // default
print("x is neither 1 nor 2")}}Copy the code
- A collection of traverse
// Recommended usagefor (item in items) {
println(item)
}
Copy the code
or
// Recommended usagefor ((key, value) in map) {
println("$key -> $value")}Copy the code
Or determine whether the set contains
when {
"orange" in items -> println("juicy")
"apple" in items -> println("apple is fine too")}Copy the code
Or use lambda expressions to filter and map collections:
val fruits = listOf("banana"."avocado"."apple"."kiwifruit")
fruits
.filter{ it.startsWith("a") }
.sortedBy { it }
.map { it.toUpperCase() }
.forEach { println(it) }
Copy the code
- The “new” keyword is not required to create objects
Val Rectangle = Rectangle(5.0, 2.0)Copy the code
#### idiom
- Creating an entity Class
// It is recommended that the entity class have a default parameter data class Customer(val name: String =)"", var email: String = "")
var customer: Customer = Customer("chentong"."7045xxx")
println(customer.toString())
var customer01: Customer = Customer(name="kk")
customer01.email = "1986xxx"Println (customer01.tostring ()) var customer02: Customer = Customer(name="tong",email="890xxx")
println(customer02.toString())
var customer03: Customer = Customer("3")
customer03.email = "1986xxx"
println(customer03.toString())
var customer04: Customer = Customer()
println(customer04.toString())
Copy the code
1) comes with getters, setters, toString, hashcode methods. 2) Val (read only) has no setter methods. 3) If the generated class needs to have a constructor with no arguments, all properties must specify default values
- Function default arguments
fun foo(a: Int = 0, b: String = "") {... }Copy the code
- Filter list(filter)
val listdata = listOf(1, 2, 3, -1)
println(listdata.toString())
var newdata = listdata.filter{ it > 0 }
println(newdata.toString())
Copy the code
- The map to create
// Print map funprintMap(map: Map<String,Any? >) {for ((key, value) in map) {
println("$key -> $value"Var map = HashMap<String,Any? >() map.put("chen"."tong")
map.put("yang"."yue")
printMap(map) var map01 = mutableMapOf<String, Any? >() map01["chen01"] = "tong"
map01["yang01"] = "yue"
printMap(map01)
var map02: HashMap<String,String> = HashMap()
map02.put("chen02"."tong")
map02.put("yang02"."yue")
printMap(map02)
var chen03 = "tong"
var yang03 ="yue"
var yuan03 = "dong"Var map03 = mutableMapOf("chen03" to chen03, "yang03" to yang03,"yuan03" to yuan03)
printMap(map03) val map04: MutableMap<String, Any? > = mutableMapOf() map04.put("chen04"."tong")
map04.put("yang04"."yue")
map04["yuan04"] = "dong"
printMap(map04)
Copy the code
The first method is strongly recommended for the following reasons: 1. Simple and clear syntax; 2. Consistent with Java, low cost and easy to understand; 3
- The list to create
/ / the list to print funprintList(list: List<Any? >) {for (item in list) {
println("$item")
}
println("===end===")
}
val lists = listOf("lists"."123"."456"// No add methodprintList(lists) var lists01 = ArrayList<String>() lists01.add()"lists01")
lists01.add("banana")
printList(lists01)
val lists02: MutableList<String> = mutableListOf("lists02"."02121")
lists02.add("testadd")
printVar lists03: MutableList<String> = mutableListOf() lists03.add()"lists03")
lists03.add("676767")
printList(lists03)
Copy the code
Recommend the second, the fourth writing method, clear, concise
- A read-only list map
val list = listOf("a"."b"."c")
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
Copy the code
- Access to the map
var map = HashMap<String,String>()
map.put("chen"."tong")
map["zhang"] = "san"
println(map.get("zhang"))
println(map.get("chen"))
println(map["zhang"])
println(map["chen"])
Copy the code
Quick access is recommended at 👇
println(map["key"])
map["key"] = value
Copy the code
- Lazy properties
Val p: String by lazy {// compute the String}Copy the code
- To create a singleton
object Resource {
val name = "Name"
}
Copy the code
##### Safety judgment
- If not null abbreviation
val lists = listOf("123") println(lists? .size)Copy the code
- If not null{} else{} abbreviation
val lists = listOf("123") println(lists? .size ? :"empty")
println("Content"? :"empty") println(null ? :"empty")
Copy the code
- if not null
val lists = listOf("123") lists? .let {// the code will execute here if data is not null println(lists. Size)}Copy the code
- Return when expression
fun transform(color: String): Int {
return when (color) {
"Red"- > 0"Green"- > 1"Blue"- > 2else -> throw IllegalArgumentException("Invalid color param value")
}
}
println(transform("Red"))
println(transform("1"))
Copy the code
- Single-expression usage
Fun theAnswer() = 42 // = fun theAnswer(): Int {return42}Copy the code
- One object calls multiple methods
class Turtle {
fun penDown(){
println("penDown()")
}
fun penUp(){
println("penUp()")
}
fun turn(degrees: Double){
println("turn($degrees)" )
}
fun forward(pixels: Double){
println("forward($pixels)"}} val myTurtle = Turtle() with(myTurtle) {// Draw a 100 pixel square penDown()for(i in1.. 4) {forward(100.0) turn(90.0)} penUp()}Copy the code
- Try, if, and when expressions are preferred
return if (x) foo() else bar()
return when(x) {
0 -> "zero"
else -> "nonzero"
}
Copy the code
The following code is not recommended
if (x)
return foo()
else
return bar()
when(x) {
0 -> return "zero"
else -> return "nonzero"
}
Copy the code
If applies to two conditions and when applies to multiple conditions