How to quickly master Kotlin by Java programmers who understand Kotlin in seconds

[Copyright Statement] The source can be freely reprinted for non-commercial purposes.
Blog address: https://blog.csdn.net/ShuSheng0007/article/details/108640462
from: shusheng007

Article first published on personal blog

Overview

Kotlin/JVMIt can be seen as an active attempt to improve Java, which attempts to improve the known shortcomings and shortcomings of the Java programming language that have been widely discussed. Because I was engaged in the development of C# many years ago. When I first saw Kotlin, I felt that many features of C# existed many years ago. It shows how traditional Java is and is unwilling to introduce too much syntactic sugar.

Regarding the love and hatred between Kotlin and Java, please click here to see if you have the opportunity to write a related article. This article only wants to give some differences between Kotlin and Java from the perspective of Java idiots, which is often crucial for Java idiots to quickly master Kotlin. Because Kotlin is an improvement of Java, it is 100% interoperable with Java, so Java programmers can often get started quickly after a brief familiarity, and then become proficient in Kotlin.

A very important way for humans to learn new things is analogy. If the new things are very similar to the old things, then the effect of learning by analogy will be more obvious. From Java to Kotlin fits this feature very well, and analogy with Java you are familiar with. The familiar Kotlin will do more with less, let's get started.

This article is based on Kotlin 1.4.0 version

Grammatical differences

There are some grammatical differences between Kotlin and Java, which are not particularly huge. Here are the few that I think most need to adapt:

Kotlin methods and properties may not be included in the category of

We know that everything in Java is based on classes and must be in classes, but Kotlin is not. In the following code, methods, attributes, and classes coexist at the same level , and they are all allowed in the same file.

//属性
var name: String = "ShuSheng007"

//方法
fun sum(x: Int, y: Int): Int {
    return x + y
}

//类
class Student{}

Statements in Kotlin do not need to ;end with

println("hello world")

Data types in Kotlin are postfix

//变量声明时类型后置
var name: String = "ShuSheng007"

//方法参数及返回值类型后置
fun sum(x: Int, y: Int): Int {
        return x + y
}

Kotlin method uses funkeyword definition

fun sum(x: Int, y: Int): Int {
        return x + y
}

Kotlin's classes and methods are public finalby default

The class cannot be inherited by default, and the methods in the base class cannot be overridden by default. If you want to be inherited or overridden, you need to openmark it with keywords

//Human类可以被继承
open class Human{
	//eat方法可以被overwrite
    open fun eat(){
    }
}

Class inheritance and interface implementation in Kotlin use :tags

//类继承
class Man : Human(){
    override fun eat() {
        super.eat()
    }
}

//实现接口
interface action{
    fun sleep()
}
class Woman :action{
    override fun sleep() {
        //...
    }
}

Use in Kotlin var, valdeclare variables and attributes, and can perform type inference

In Java, we declare a variable must first specify its type, for example

String name= "shusheng007";

But in Kotlin, the compiler can automatically infer its type based on the assignmentString

var name = "shusheng007"

Kotlin has non-null and nullable types

This is also a highlight of its propaganda, trying to solve a problem worth billions of dollars:NullPointerException

Every object in Kotlin is non-null by default, unless you explicitly declare it as nullable

//非空类型
var name1:String="shusheng"
//可空类型
var name2:String?=null

The package in Kotlin can be inconsistent with the file path

What does that mean? Suppose we have a class file in the src/.../top/ss007/learn file path

Then for Java, the package name must be

package top.ss007.learn

For Kotlin, there is no such restriction, you can call it whatever you want, for example: it 's so self-willed

package just.so.wayward

It's really headstrong, so it's better to follow the Java specification.

There is no Checked Exception in Kotlin

There are many checked exceptions in Java, and programmers are forced to deal with it, or thrown to the lower caller for processing. But Kotlin does not have this restriction.

Kotlin emphasizes the concept of immutability

Kotlin will give priority to immutable objects, such as immutable collections and immutable variables. After these immutable objects are generated, they can only be read but not modified. As for the use of immutable objects, there are many benefits, such as its natural thread safety, etc.

The above are the differences that I personally think are the most subversive of our cognition. After familiar with the above, Java programmers can basically understand the code of Kotlin.

Features that do not exist in Java

Kotlin has introduced many features that do not exist in Java. Here are a few that I think are more important

Function Type

In Kotlin, a method is a first-class citizen, which means that a method is the same as a class. The method can do everything the class can do. A method can be used as a type as the parameter of other methods, as the return value type of other methods, as the declaration type of a variable... This subverts the three views of Java programmers. There is no corresponding concept in Java. If you have to find a counterpart, it is a functional interface.

The following is a method type (two int data get an int, for example, 1+2=3). We can completely regard it as a class in java. This guy is applicable to all the places where the class can be used. That is to say, in Kotlin, methods can be passed as parameters, which is equivalent to implementing method references, which is awesome. .

(Int, Int) -> Int

For example, in the following method, operationthe type of the third parameter is the method type above

fun calculate(x: Int, y: Int, operation: (Int, Int) -> Int): Int {  
    return operation(x, y)                                          
}
//如何调用
fun sum(x: Int, y: Int): Int {
    return x + y
}
//将sum方法当参数传入了calculate方法中
calculate(4, 5, ::sum)

//我们也可以使用Lambda表达式
calculate(4, 5, { a, b -> a + b })
//当Lambda表达式是方法的最后一个参数时,其可以移到()外面
calculate(4, 5) { a, b -> a + b }

So how to achieve the same function in Java?

Step 1: Define a function interface according to the requirements

The following interface has only one abstract method, which is a functional interface.

@FunctionalInterface
public interface Fun2<P1, P2, R> {
    R invoke(P1 p1, P2 p2);
}

Step 2: Use it as a method parameter type

 public int javaCalculate(int x, int y, Fun2<Integer, Integer, Integer> operation) {
     return operation.invoke(x, y);
 }

After the above two steps, it is done.

When calling a method in Java in Kotlin javaCalculate, the IDE will prompt the following information
Insert picture description here

The first is to tell you that the third parameter can use the function type in Kotlin, the code is as follows

javaCalculate(4, 5) { a, b -> a + b }

The second one is more orthodox, telling you that you need a parameter of type Fun2, the code is as follows

javaCalculate(4, 5, object : Fun2<Int, Int, Int> {
        override fun invoke(p1: Int, p2: Int): Int {
            return p1 + p2
        }
    })

In Java we use newan object of an anonymous class, while in Kotlin we need to use objectkeywords

Property (Property)

var name:String="ShuSheng007"

Corresponding to the private field (Field) in the Java class plus the gettersum settermethod

private String name;

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}

Data class

data class User(val name: String, val age: Int)

Roughly equivalent to JavaBean in Java, but with subtle differences, this is also a housekeeping feature often displayed when Kotlin promotes its simplicity

Sealed class ( Sealed the Classes )

This is pretty awesome, there is no corresponding stuff in Java, and it is mainly whenused in Kotlin . When I first saw it, I didn't like it very much, because it was called a sealed class, but it could be inherited. Later, I discovered the subtlety of its design, and it really solved the dilemma often encountered in development.

It is a class with limited inheritance, such as the following Human class, which has the following characteristics

  1. It is an abstract class
  2. It cannot be instantiated directly
  3. Its subclass must be in the same file as it
sealed class Human {
    abstract fun eat(): Unit
    open fun program(){
        println("I use koltin")
    }
}
class Man : Human() {
    override fun eat() {
    }

    override fun equals(other: Any?): Boolean {
        return this === other
    }

    override fun hashCode(): Int {
        return System.identityHashCode(this)
    }
}

class Woman :Human(){
    override fun eat() {
    }

    override fun program() {
        super.program()
    }
}

What are its benefits? It is mainly used in whenexpressions. It has the same function as enumeration, but it can protect state. Enumeration is singleton.

Extension functions and extension properties

This feature is also a very important feature of Kotlin and has a wide range of applications. Through extension methods, Kotlin has the ability to add new methods and properties to a class without inheritance

For example, we want to implement one wrapWithSymbol, used to add before and after the string <>, how to achieve it? If it is Java, you can only write a Utils method, and Kotlin can use extension methods to Stringadd a new method to the class.

The implementation method is as follows, pay attention to the type to be extended in front of the method, the scientific name is receiver

fun String.wrapWithSymbol() :String{
	return "<$this>"
}

//使用
println("my name is ${"shusheng007".wrapWithSymbol()}")

Output:

my name is <shusheng007>

It can be seen that it has been added before and after the target string <>. From the call method, the wrapWithSymbolmethod is just Stringlike the method of the class.

Extension attributes are similar to extension methods:

val <T> List<T>.lastIndex: Int
    get() = size - 1
    
//调用
println(listOf(1,2,3,4).lastIndex)

Operator overloading

This is actually quite complicated and easy to be abused. I think it should belong to advanced knowledge. Here is just a brief introduction.

Java does not support operator overloading, in fact, it does not affect the overall situation.

So what is operator overloading? To understand this problem, you must first understand what an operator is?

For example, we often use the programming time a++, a--, a+b, a==b ,a in band so on, which of those ++,--,+,== ,inis the operator.

So what is overloading? These operators themselves all have their own meaning, but we can change the meaning of these operators through overloading. This process is called operator overloading.

In Kotlin, the set of operators that can be overloaded and their corresponding methods are predefined and cannot be overloaded casually. One of them is listed below:

Expression Translated to
a + b a.plus(b)
a - b a.minus(b)
a * b a.times(b)
a / b a.div(b)
a % b a.rem(b), a.mod(b) (deprecated)
a…b a.rangeTo (b)

Operator overloaded methods can be either instance methods or extension methods.

Let's try to reload the +operators in the above table using instance methods . There are two points to note:

  1. Overloaded methods must be operatormarked with
  2. The overloaded method name and parameters must be predefined by Kotlin, for example here plus
data class Point(val x: Int, val y: Int){
	operator fun plus(p: Point): Point {
        return Point(p.x + x,p.y + y)
    }
}

//调用
 val p1 = Point(1, 2)
 val p2 = Point(3, 4)
 println(p1 + p2)

Output:

Point(x=4, y=6)

It can be seen that by overloading the +operator, we have changed its inner meaning so that +it can also be used for objects.

Coroutine

More complicated, need a separate article description

to sum up

As the saying goes, seeking common ground while reserving differences, learning by analogy, everything in the world is the same. It's time to like and collect again. Like is to support the author, and the collection is responsible for yourself.

Let go of one thought and feel at ease.

Guess you like

Origin blog.csdn.net/ShuSheng0007/article/details/108640462