preface
This article focuses on constants and variables, branch expressions, operator and infix expressions, Lambda expressions, case: Equals and hashCode for Person, case: Four operations for String
List of Kotlin articles
List of Kotlin articles: Click here to jump to see
directory
(1) Constants and variables
(1) Variables
Java:
int a = 2;
a = 3;
final int b = 3; // Read-only variables
Copy the code
Kotlin:
var a = 2
a = 3
val b = 3 // Read-only variables
Copy the code
(2) Constant
Java:
static final int b = 3;
Copy the code
Kotlin:
const val b = 3
// Can only be defined in the global scope
// Only primitive types can be decorated
// Must be initialized immediately with a burst volume
Copy the code
(2) Branch expression
(1) the if… else…
Java:
if (a == 3) {
c = 4;
} else {
c = 5;
}
c = a == 3 ? 4 : 5;
Copy the code
Kotlin:
if (a == 3) {
c = 4
} else {
c = 5
}
c = if (a == 3) 4 else 5
Copy the code
(2) the when…
Java:
switch (a) {
case 0:
c = 5;
break;
case 1:
c = 100;
break;
default:
c = 20;
}
Copy the code
Kotlin:
c = when (a) {
0 -> 5
1 -> 100
else -> 20} if a is equal to0C =5If a =1C =100.var x: Any = Any()
c = when {
x is String -> x.length
x == 1 -> 100
else -> 20
}
c = when(val input = readLine()){
null -> 0
else -> input.length
}
Copy the code
(3) Try… catch
Java:
try {
c = a / b;
} catch (ArithmeticException | NullPointerException e) {
e.printStackTrace();
c = 0;
}
Copy the code
Kotlin:
try {
c = a / b
} catch (e: Exception) {
e.printStackTrace()
c = 0
}
c = try {
a / b
} catch (e: ArithmeticException) {
2 // If an exception is thrown, c = 2
} catch (e: Exception) {
e.printStackTrace()
0 // If an exception is thrown, c = 0
}
c = try {
a / b
} catch (e: ArithmeticException) {
2
} catch (e: Exception) {
e.printStackTrace()
0
}
Copy the code
(3) operator and infix expression
(1) Operators officially provided by Kotlin
"Hello"= ="World"
"Hello".equals("World")
2 + 3
2.plus(3)
val list = listOf(1.2.3.4)
2 in list
list.contains(2)
val map = mutableMapOf(
"Hello" to 2."World" to 3
)
val value = map["Hello"]
// val value = map.get("Hello")
map["World"] = 4
map.set("World".4)
2 > 3
2.compareTo(3) > 0
val func = fun(a) {
println("Hello")
}
func.invoke()
func()
2 to 3
2.to(3)
Copy the code
(2) Infix expression
The number of operators is limited, and although it changes with Kotlin iterations, it is still fixed for developers, so when I run out of operators I need to extend the logic we need in the form of infix expressions. The two points are infix and the function name (rotate)
println("HelloWorld" rotate 5) // Extend the rotate function
infix fun String.rotate(count: Int): String {
val index = count % length
return this.substring(index) + this.substring(0, index)
}
val book = Book()
val desk = Desk()
book on desk
class Book
class Desk
infix fun Book.on(desk: Desk){}Copy the code
(4) Lambda expression
(1) Anonymous function
Ordinary functions:
fun func(a) {
println("Hello")}Copy the code
Anonymous functions :(no function name)
fun(a) {
println("Hello")}Copy the code
Use of anonymous functions:
val func = fun(a) { // func is the variable name
println("Hello")
}
func() // Call a function with a variable
Copy the code
The type of the anonymous function :(the anonymous function is the type of the value returned in the last line)
val func: () -> Unit = fun(a) {
println("Hello")}Copy the code
(2) Lambda expressions
Lambda expressions in Kotlin are essentially anonymous functions. The appearance of Lambda does reduce the amount of code to write, and also makes the code more concise
val func: () -> Unit = fun(a) {
println("Hello")}val lambda: () -> Unit = {
println("Hello")}val f1 = { p: Int ->
println(p)
"Hello"
}
Copy the code
Example: Implement Equals and hashCode for Person
class Person(val age: Int.val name: String) {
override fun equals(other: Any?).: Boolean {
val other = (other as? Person) ? :return false
return other.age == age && other.name == name
}
override fun hashCode(a): Int {
return 1 + 7 * age + 13 * name.hashCode()
}
}
fun main(a) {
val persons = HashSet<Person>()
(0.. 5).forEach {
persons += Person(20."Benny")
}
println(persons.size) / / 1
}
Copy the code
(6) Case: Implement four operations for String
operator fun String.minus(right: Any?).
= this.replaceFirst(right.toString(), "")
// Replace the first occurrence of "right" in the string with empty
For example, if the string is HelloWorld World and right is Hello, the result is World World
operator fun String.times(right: Int): String {
return (1..right).joinToString("") {this }
// Repeat the character passed right, separated by a space (can also be separated by a ",")
}
operator fun String.div(right: Any?).: Int {
val right = right.toString()
// The first argument: the length of the string passed in
// Second argument: the number of backward steps (starting from the first, if the argument is 1, then the next position after the end is 2)
// The third argument: is it equal to the string passed in
If He is equal to ld, then it + 1; if not, move backwards one bit
// Determine if el is equal to ld, if it is equal, it + 1, if not, move back one bit
return this.windowed(right.length, 1, transform = {
it == right
}) // [false, false, false, false ... false, true, ..., true]
.count { it }
}
fun main(a) {
val value = "HelloWorld World"
println(value - "World")
println(value * 2)
val star = "*"
println("*" * 20)
println(value / 3)
println(value / "l")
println(value / "ld")}Copy the code
Results:
Hello World
HelloWorld WorldHelloWorld World
********************
0
4
2
Copy the code