preface
At present, Kotlin has been fully used in the company’s projects, and the transition process is not very comfortable, but we are glad that the outcome is satisfactory. Kotlin does make code clean, secure, and efficient. Here are some of the comfort points in using Kotlin.
- Character template
- Air safety
- Lazy loading
- Easy to read loop
- Powerful and easy to use iterators
- The default parameters
- DataClass
- Short and powerful library of standard functions
- All-in-one WHEN (combined with sealed classes to make code more comfortable)
- extension
- Simple Bundle fast Parcelable
- To be continued..
Character template
In the development, it is inevitable to splice a string according to multiple fields. When the data logic is too long or too complex, it is too long to be realized with Java. Kotlin simplifies this process by placing $before variable names to express variables and expressions in strings.
val str = "hello"
// str length : 5
print("$str length: {$str.length}")
Copy the code
Air safety
In the process of using Java to develop Android, it is inevitable to have a large number of empty security check code, because Kotlin is very compatible with Java, in this problem Kotlin designed a whole new type system (not studied here) to improve and optimize it.
High standard, rigorous use of variables, is a normative requirement
Elvis operator
Null value is
// Non-nullable type (must be initialized before use)
var notCanNullInt: Int = 0
// Nullable type
var canNullInt: Int? = null
// Secure access
print("${canNullInt? .toShort()}")
// Avoid giving a default value for null
valage = canNullInt ? :18
// returns null
valtime = canNullInt ? :return
Copy the code
Lazy loading
This is a further refinement of non-nullable types, as there are always variables that are initialized at some point in development rather than being loaded at class load time. Lazy loading is a nice thing to save on initialization costs and initialize variables only when they are really needed.
val userInfo: UserInfo by lazy { UserInfo() }
lateinit var person: InvationPerson
Copy the code
Easy to read loop
Kotlin has the concept of intervals, which makes creating loops easier to read.
// print :0 1 2 3 4 5 6 7 8 9 10
for (i in 0.10.) {
print("$i ")}// print :10 9 8 7 6 5 4 3 2 1 0
for (i in 10 downTo 0) {
print("$i ")}// print :0 2 4 6 8 10
for (i in 0.10. step 2) {
print("$i ")}// print :0 1 2 3 4 5 6 7 8 9
for (i in 0 until 10) {
print("$i ")}val map = mapOf("a" to 1."b" to 2)
// print :a - 1 b - 2
for ((key, value) in map) {
print("$key - $value")}Copy the code
Powerful and easy to use iterators
Traversal collections is fundamental, and Java is not friendly for slightly more complex data logic. Of course, RxJava came later to remedy this, but Kotlin seems to have done it a little better. (Kotlin’s collection framework architecture will not be discussed here.)
val list = listOf(1.2.3.4.5.6.7.8.9)
list.forEach { print(it) }
/ / map
val listUp = list.map { it + 2 }
/ / filter
val listFilter = list.filter { it % 2= =0 }
// Map filter traversal operations exist in asSequence lazy processing. AsSequence can combine them to only one traversal to improve performance
val listMore = list.asSequence().map { it + 2 }.filter { it % 2= =0 }.toList()
Copy the code
AsSequence is a great way to improve efficiency, but other operations are not listed
The default parameters
Overloading is a fairly common operation, but sometimes this approach results in much of the same template code. Kotlin’s default arguments, which can be assigned default values and are called as variables rather than sequentially passed values as in Java. And because of the default values, the call can be passed on a case-by-case basis, making it more flexible, readable, and concise.
class Point(val x: Float = 0F, val y: Float = 0F)
val x = Point(x = 10F)// x 10 y 0
val y = Point(y = 10F)// x 0 y 10
val xy = Point(x = 10F, y = 10F)// x10 y10
Copy the code
DataClass
Bean files are essential for development, but Java Bean files are mostly template code, which is generated automatically by plug-ins. Kotlin can declare these classes as Data classes, which by default implement equals(), hashCode(), The toString() and copy() methods range from a few dozen lines of Java code to a few lines of code, with Kotlin declaring only one data class
data class Person(
val name: String,
val age: Int.val sex: Int) {//....
}
Copy the code
Short and powerful library of standard functions
This is the function library provided by Kotlin, which will simplify a lot of boilerplate code. The slightly different points are that their “this” and “it” point to different values, and return values are different. Use them according to the specific situation.
run
val str = "a"
val res = str.run{
// This points to "a"
// You can access the properties of the object directly
print(length)
1 // The last line returns 1
}
Copy the code
let
val str = "a"
val res = str.let{
// this points to the current class
// it points to a
print(it.length)
"let" // return value "let"
}
Copy the code
with
val res = with(user){
// this points to user
println(age)
println(name)
"with" / / the return value
}
Copy the code
apply
val str = "a"
val res = a.apply{
// This points to a
2 / / the return value
}
Copy the code
Skills in the when
I am familiar with Java’s Stwich, but it has many restrictions in use and sometimes seems weak in the face of complex logic. Kotlin’s when expressions can match almost anything (literals, enumerations, numbers, ranges, types, expressions, and even functions (Kotlin functions come first)).
fun whenTest(number: Number?).: String {
return when (number) {
null.0 -> "empty"
1 -> "tiny"
in 2.. 5 -> "small"
is Long -> "big number"
else -> "unKnow"}}Copy the code
Of course sometimes use the when there will be some more troublesome thing, such as processing, on the else because you clearly only so several ways of applications, but you have to write about the else processing, such code let a person feel not at ease, also reduces the readability, this time can combine Koltin sealed class to deal with, For example, the network situation of receipt, error processing, Android to RecyclerView adaptation of ViewHolder processing
// The existence of the sealing class makes the whole process more rigorous
sealed class NetWorkResult
data class Success(val resJson: String) : NetWorkResult()
data class Failure(val error: Error) : NetWorkResult()
// The code is more readable
fun netWorkTest(result: NetWorkResult) {
when (result) {
is Success -> {
showResult(result.resJson)
}
is Failure -> {
showError(result.error)
}
}
}
Copy the code
extension
Extensions are probably the most popular feature because they allow you to write fewer utility classes and make your code look more readable and concise. For example, do something to prevent double clicking.
// Extend click event properties (repeat click duration)
var <T : View> T.lastClickTime: Long
set(value) = setTag(1766613352, value)
get() = getTag(1766613352) as? Long? :0
// Click the event binding again
inline fun <T : View> T.singleClick(time: Long = 800.crossinline block: (T) -> Unit) {
setOnClickListener {
val currentTimeMillis = System.currentTimeMillis()
if (currentTimeMillis - lastClickTime > time || this is Checkable) {
lastClickTime = currentTimeMillis
block(this)}}}Copy the code
Simple Bundle fast Parcelable
I didn’t notice this feature at first because the project was component-based and used ARouter for all the jump transfers, but I was happy to see what Kotlin had done with it
// Creating bundles is as elegant as creating maps
val bundle = bundleOf(
"KEY_ONE" to 1."KEY_TWO" to 2L,
"KEY_THREE" to true
)
// No more tedious Parcelable implementations
@Parcelize
data class Person(val name:String):Parcelable
Copy the code
To be continued..
Having developed two full projects using Kotlin, Kotlin really brings syntactic sugar to the development experience, making development more efficient and making the code easier to read. Of course, here is only my temporary thought of some places, if there are more better usage, welcome to inform ~