Kotlin is better than Java, what we have to say

Kotlin advantages

Kotlin is safer.
This is its most important advantage. Null references are controlled by the type system, and you will never encounter NullPointerException again. This null pointer exception is like a hidden time bomb, which may explode anytime.

To call Java code in Kotlin, non-empty annotations are required in Java code.

The code is concise.
Use Lambda expressions to save a lot of last class code, especially the redundant findViewById. It is said that less code can reduce errors.

Functional support The
use of higher-order functions can be used as return values ​​or parameter values, which is particularly convenient.
What is a higher order function? It takes a function as a parameter and a function as a return value is a higher-order function, and each function corresponds to a Lambda expression.
Common higher-order functions map(), forEach(), flatMap(), reduce(), fold(), filter(), takeWhile(), let(), apply()

The extension function
Kotlin is similar to C#, which can extend the new functions of a class without inheriting the class or using any type of design pattern like decorators. Kotlin supports extended functions and extended attributes.
1) Expressions can be directly used as function return values
2) Extended functions: fun class name. Extended method name (parameter list) {method body} or fun class name. Extended method name (parameter list) = expression

fun MyClass.add(a:Int,b:Int) = a+b

3) Extended attributes: var class name. Extended attributes / corresponding to other methods

var MyClass.d: String
    get() = "sdasda"
    set(value){
    
    d = value}//MyClass的扩展成员变量d

There is no static member in Kotlin, the
corresponding solution is the companion class


The standard library of Kotlin that can call each other with java is more an extension of the Java library, but the Android library can be used in Kotlin. You can call each other in Kotlin and Java code, perfect barrier-free.

Difference from Java

  1. The basic types are similar, and the unboxing and packing process no longer exists
  2. Variable declarations are only var variable variables and val read-only variables. Kotlin can automatically and intelligently determine the data type of the variable
  3. Java supports char>int>long automatic conversion, in order to reduce unnecessary errors, it is not supported in Kotlin
  4. The original class in Java is Object, but in Kotlin, there are only equals(), hashCode, and toString methods in the Any method.
  5. Type conversion in Java refers to the existence of an inheritance relationship. Subclasses can be automatically transformed into a parent class, while the parent rotor class requires forced conversion. The type conversion in Kotlin uses the as keyword
  6. There are multiple same class names in Java, and the package name. The class name is required for reference. In Kotlin, use the following
import A.Student as AS//将A包下的Student类取外号为"AS"
import B.Studnet as BS//将B包下的Student类取外号为"BS"
  1. Kotlin has a unique range class called Range. For example with integer interval:
var intRange:IntRange = 0..1024//区间为[0,1024],注意是全闭的
var intRange2:IntRange = 0 until 1024//区间为[0,1024),注意是半闭半开的,包头不包尾

println("50是否存在与区间[0,1024]:"+intRange.contains(50))
println("-3是否存在与区间[0,1024):"+intRange.contains(-3))

//遍历区间
for(i in intRange){
    
    
    println(i)
}
  1. In Kotlin, the general declaration of arrays starts with intArrayOf and arrayOf to declare

  2. Kotlin's permission modifier has no default, and the corresponding one is changed to internal

  3. Use in Kotlin ""Equivalent to the equals() method in Java. Use"="To be equivalent to Java"==", compare whether two references are the same object.

  4. There is no Switch statement in Kotlin. It is replaced by when. It is more powerful. Its judgment value can be an expression.

  5. The constructor in Kotlin needs to use the keyword constructor, or there is a special default construction method, which is called the main constructor

class Student(var name:String,var age:Int)//构造器的特殊写法
  1. In Kotlin, functions that are subordinate to classes are called "member methods", and those that are not subordinate to classes are called functions. For example, the following parameters are expressed in the form of method blocks, this is a "function"

  2. Kotlin's default access permission is public, not the default access permission default in Java.
    final: is Kotlin's default modifier. If you want your class to be inherited, you need to use open to modify it.
    data: This modifier is very useful and unique. After being modified with data:
    1) All members are automatically declared with operator, and getters and setters are automatically generated for members.
    2) The equals()/hashCode() and toString() methods are automatically rewritten.
    3) The data class does not have a parameterless constructor, which feels like a pit, so Kotlin officially gave a solution, which is to use NoArg (parameterless constructor ) And AllOpen (can be inherited) to solve the problem.

  3. In the Kotlin interface, you can implement methods without reporting errors. The following errors will be reported in Java, but no errors will be reported in Kotlin.

interface JieKou{
    
    
    fun A(){
    
    
       //方法体a
       println("接口里面的方法,我是方法体")
    }
}
  1. In the inner class of the class, the keyword inner needs to be added, otherwise the class is static by default. The conflict of this keyword for non-static inner classes can be distinguished by using "this@external class name".
var ab  = A.AB()   //实例化A类中的静态内部类AB
var ac  = A().AC() //实例化A类中的非静态内部类AC

A a=new A();
A.AC ac =a.new AC();

A.AC ac=new A.AC();
  1. Package-level functions, functions outside of Kotlin's class names, are package-level functions. All functions of package-level functions (including extension functions) are static. When compiling, Kotlin puts all package-level functions in one class, and Java can access all packages by such names Level functions, such as Test.getMessage()
//文件名  Test.kt
class Student(var name:String,var age:Int){
    
    
}

fun getMessage(){
    
    //这个扩展方法被编译Test.kt中的静态方法public static getMessage(Student student)
    println("")
}

  1. The wildcard in Kotlin is not "?", but "*". "?" is used to judge non-empty
  2. Regular expressions, in addition to the traditional way in Java, there is a new way is to use
var results = Regex(geShi).split(str)//Regex为Kotlin中处理正则表达式的工具类
  1. Use "use" in IO stream to automatically close read and write files

Pros and cons of Kotlin in Android

Some of the advantages of Kotlin said earlier, to add here the advantages and disadvantages in the use of Kotlin Android and Java to make comparative
advantages

  1. Kotlin supports multiple platforms and Jetpack Compose UI, but Java does not. For Android development, please become familiar with the various supports provided by Jetpack as soon as possible

Disadvantage

  1. The speed of the Kotlin compiler is a little slower than that of Java. This point is being optimized and improved. I believe that the speed difference will not be too big after continuous optimization.

Companion class

I need to explain this feature separately. There is no static in Kotlin. The variables and methods in the companion class are equivalent to static variables and static methods.

  companion object {
    
    //静态方法和变量都应该写在这里面
        var  a:Int =  3;//静态变量
        fun get():Int{
    
    
            return a
        }
    }

Several annotations in Kotlin

1.@JavaFiled: compile attributes into Java variables

2.@JvmStatic: Compile the method of the object into a Java static method, usually used with companion objects

3.@JvmOverloads: Default parameter generation overload method

4.@file:JvmName: Specify the compiled class name of the Kotlin file

Inline function

The let
let extension function is actually a scope function. When you need to define a variable in a specific scope, let function is a good choice; another function of let function is to avoid writing some null judgments Operation.

//1)判断object为null的操作
object?.let{
    
    //表示object不为null的条件下,才会去执行let函数体
   it.todo() //在函数体内使用it替代object对象去访问其公有的属性和方法
   1000
}

The object can be referred to by it in the function block. The return value is the last line of the function block or the return expression is specified.

Its usage scenarios are as follows:
Scenario 1: The most commonly used scenario is to use the let function to process a nullable object uniformly.
Scenario 2: Then it is necessary to clarify that a variable can be used in a specific scope

The with
with function is slightly different from the previous functions because it does not exist in an extended form. It takes an object as a parameter of a function, and this object can be referred to in the function block through this. The return value is the last line of the function block or the return expression is specified.
The following two codes are equivalent:

val result = with(user, {
    
    
        println("my name is $name, I am $age years old, my phone number is $phoneNum")
        1000
})

val result = with(user) {
    
    
        println("my name is $name, I am $age years old, my phone number is $phoneNum")
        1000
}

Usage scenario It is
suitable for calling multiple methods of the same class. You can save the repetition of the class name and directly call the method of the class. It is often used in the onBinderViewHolder in the RecyclerView in Android, and the attributes of the data model are mapped to the UI.

override fun onBindViewHolder(holder: ViewHolder, position: Int){
    
    
   val item = getItem(position)?: return
   
   with(item){
    
    
      holder.tvNewsTitle.text = StringUtils.trimToEmpty(titleEn)
	   holder.tvNewsSummary.text = StringUtils.trimToEmpty(summary)
	   holder.tvExtraInf.text = "难度:$gradeInfo | 单词数:$length | 读后感: $numReviews"
       ...   
   
   }

}

The run
function can actually be said to be a combination of let and with. The run function only accepts a lambda function as a parameter and returns in the form of a closure. The return value is the value of the last line or the specified return expression.

override fun onBindViewHolder(holder: ViewHolder, position: Int){
    
    
   
  getItem(position)?.run{
    
    
      holder.tvNewsTitle.text = StringUtils.trimToEmpty(titleEn)
	   holder.tvNewsSummary.text = StringUtils.trimToEmpty(summary)
	   holder.tvExtraInf = "难度:$gradeInfo | 单词数:$length | 读后感: $numReviews"
       ...   
   }
}

Applicable to any scenarios with let and with functions. Because the run function is a combination of let and with functions. To be precise, it makes up for the fact that the let function must use the it parameter in the function body to replace the object. In the run function, it can be omitted like the with function, and directly access the public attributes of the instance. Method, on the other hand, it makes up for the problem of null judgment when the with function passes in the object. In the run function, the null judgment can be done like the let function.

apply
apply function and run function like, the only difference is the value returned is not the same as their respective Structurally, the closure is run function Returns the value of the last line of code, and apply the function returns the incoming object itself.

The following is different from the with function, and the result value result refers to user

fun main() {
    
    
    val user = User("Kotlin", 1, "1111111")

    val result = user.apply {
    
    
        println("my name is $name, I am $age years old, my phone number is $phoneNum")
        1000
    }
    println("result: $result")
}

Use scenario
1) apply is generally used when an object instance is initialized, and the properties in the object need to be assigned. Or when you dynamically inflate an XML View, you need to bind data to the View. This scenario is very common.

mSheetDialogView = View.inflate(activity, R.layout.biz_exam_plan_layout_sheet_inner, null).apply{
    
    
   course_comment_tv_label.paint.isFakeBoldText = true
   course_comment_tv_score.paint.isFakeBoldText = true
   course_comment_tv_cancel.paint.isFakeBoldText = true
   course_comment_tv_confirm.paint.isFakeBoldText = true
   course_comment_seek_bar.max = 10
   course_comment_seek_bar.progress = 0

}

2) It is also used to judge null like the let function.

to sum up

First of all, I have used Kotlin to develop in Android for more than 7 months. According to my own experience, I am more inclined to use Kotlin to develop. Of course, each user experience will be different. It is suitable for you.

I hope everyone will learn and use Kotlin before they can experience themselves and compare the advantages and disadvantages of the two. Learning to use is definitely not simply converting Java code into Kotlin through IDEA, it just uses Kotlin language to write Java, which is meaningless.

As technology developers, we should bravely embrace change and innovation, and we should not use our original preconceived notions to look at problems. Practice is the only criterion for testing all truths. Only after practicing can we gain our own.

I hope that there are objections to actively comment and leave a message, and I must reply. Right or wrong is determined in the dissent discussion, welcome to leave a message!

Guess you like

Origin blog.csdn.net/luo_boke/article/details/107172965