Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How Java engineers use Kotlin

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how Java engineers use Kotlin. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

Overview

Kotlin is a statically typed programming language running on the Java virtual machine, known as Swift of the Android world, designed and developed by JetBrains and open source.

Kotlin can be compiled into Java bytecode or into JavaScript, making it easy to run on devices without JVM.

In Google I Dot O 2017, Google announced that Kotlin has become the official Android development language.

Kotlin/JVM can be seen as a positive attempt to improve Java, which attempts to improve the known and widely discussed shortcomings and shortcomings of the Java programming language. Because I worked on the development of C # many years ago, when I first saw Kotlin, I felt that many features of C # had been available many years ago. It shows how traditional Java is and is unwilling to introduce too much grammatical sugar.

Click here not to list the love and hatred between Kotlin and Java, and so have the opportunity to write a related article separately. This paper only wants to give some differences between Kotlin and Java from the point of view of Java users, which is often very important for Java users to master Kotlin quickly. Because Kotlin is an improvement on Java and is 100% interoperable with Java, Java programmers can often get started quickly and become proficient in Kotlin after a short period of familiarity.

A very important way for human beings to learn new things is analogy. If there is a great similarity between new things and old things, then the effect of analogical learning will be more obvious, from Java to Kotlin is very consistent with this characteristic. Using your familiar Java to compare unfamiliar Kotlin will get twice the result with half the effort. Let's start.

This article is based on Kotlin version 1.4.0

Grammatical differences

There are some grammatical differences between Kotlin and Java, which are not particularly significant. Here are some of the things I think need to be adapted most:

Methods and properties in Kotlin may not be included in the class

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

/ / attribute var name: String = "ShuSheng007" / / method fun sum (x: Int, y: Int): Int {return x + y} / / Class class Student {}

Statements in Kotlin do not need to end with;

Println ("hello world")

The data type in Kotlin is post-positioned

/ / Type post var name: String = "ShuSheng007" / / method parameter and return value type post fun sum (x: Int, y: Int): Int {return x + y} when the variable is declared

The Kotlin method is defined using the fun keyword

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

The classes and methods of Kotlin are public final by default

Classes cannot be inherited by default, and methods in the base class cannot be overridden by default. If you want to be inherited or rewritten, you need to mark them with the open keyword.

/ / Human class can be inherited open class Human {/ / eat method can be overwrite open fun eat () {}}

Class inheritance and interface implementation in Kotlin use: tag

/ / Class inherits class Man: Human () {override fun eat () {super.eat ()} / / implement interface interface action {fun sleep ()} class Woman: action {override fun sleep () {/ /.}}

Var,val is used in Kotlin to declare variables and attributes, and type inference can be performed.

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

String name= "shusheng007"

But in Kotlin, the compiler can automatically infer that the type is String based on the assignment

Var name = "shusheng007"

There are non-null and nullable types in Kotlin

This is also a highlight of its publicity, trying to solve a multibillion-dollar problem: NullPointerException

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

/ / non-empty type var name1:String= "shusheng" / / nullable type var name2:String?=null

Package in Kotlin can be inconsistent with file path

What do you mean? Suppose we have a class file in src/... / top/ss007/learn file path

Then the package name for the Java class must be

Package top.ss007.learn

For Kotlin, there is no such restriction. You can call it whatever you want, such as: it is so self-willed.

Package just.so.wayward

It's really self-willed, so it's better to follow the Java specification.

There are no detected anomalies in Kotlin (Checked Exception)

There are many checked exceptions in Java, and programmers are forced to handle it or throw it to lower-level callers. But Kotlin does not have this restriction.

Kotlin emphasizes immutable concepts

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

The above are what I think are the most subversive differences in our cognition. After being familiar with the above, Java programmers can basically understand the kotlin code.

Features that do not exist in Java

Kotlin introduces a lot of features that don't exist in Java. Here are a few that I think are more important.

Method type (Function Type)

In Kotlin, a method is a first-class citizen, meaning that a method is the same as a class, and that a method can do anything that a class can do. Method can actually be passed as a type as a parameter of other methods, when a value type is returned by other methods, when a variable declares a type. This comparison subverts the values of Java programmers, and there is no corresponding concept in Java. If you have to find a counterpart, it's a function interface.

Here is a method type (two int data get an int, for example, 1-2-3). We can think of it as a class in java, and this guy applies to all the places where the class can be used, that is to say, in kotlin, the method can be passed as a parameter, which is equivalent to the implementation of a method reference.

(Int, Int)-> Int

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

Fun calculate (x: Int, y: Int, operation: (Int, Int)-> Int): Int {return operation (x, y)} / / how to call fun sum (x: Int, y: Int): Int {return x + y} / / pass the sum method as a parameter to calculate (4,5,: sum) / / We can also use the Lambda expression calculate (4,5) {a, b-> a + b}) / / when the Lambda expression is the last parameter of the method It can be moved to () outside calculate (4,5) {a, b-> a + b}

So how do you achieve the same functionality in Java?

Step 1: define a function interface according to the requirements

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

@ FunctionalInterfacepublic interface Fun2 {R invoke (P1 p1, P2 p2);}

Step 2: use it as a method parameter type

Public int javaCalculate (int x, int y, Fun2 operation) {return operation.invoke (x, y);}

It will be done after two steps above.

When the method javaCalculate in Java is called in Kotlin, IDE prompts for the following information

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 is more orthodox, telling you that you need a parameter of type Fun2, as follows

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

In Java we use an object of an anonymous class new, while in Kotlin we need to use the object keyword

Attribute (Property)

Var name:String= "ShuSheng007"

Corresponding to the private field (Field) in the Java class plus getter and setter methods

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

Data class data class

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

It is roughly equivalent to JavaBean in Java, but with slight differences, which is a housekeeping feature often displayed by Kotlin when promoting its simplicity.

Sealed class (Sealed Classes)

This is quite powerful, there is no corresponding thing in Java, it is mainly used with when 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 found that its design was exquisite, which really solved the difficulties often encountered in the development.

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

It is an abstract class that cannot be instantiated directly

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 ()}}

So what's the advantage of it? It is mainly used in when expressions, which is similar to enumerations, but it protects state, and enumerations are singleton.

Extended method (Extension functions) and extended attribute (Extension properties)

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

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

The implementation method is as follows. Note the type to be extended in front of the method, which is called receiver.

Fun String.wrapWithSymbol (): String {return "} / / use println (" my name is ${"shusheng007" .wrapWithSymbol ()} ")

Output:

My name is

You can see that it has been added before and after the target string, and from the way it is called, the wrapWithSymbol method is like a method of the String class.

Extension properties are similar to extension methods:

Val List.lastIndex: Int get () = size-1 / / call println (listOf). LastIndex)

Operator overload

This is actually quite complex, but also easy to be abused, I think it should belong to advanced knowledge, here is only 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, when we program, we often use aplomb, in, in, etc., where + +,--, +, = =, and so on are operators.

So what is overloading? These operators themselves have their own meaning, but we can change the meaning of these operators by overloading, a process 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 these groups is listed below:

ExpressionTranslated toa + ba.plus (b) a-ba.minus (b) a * ba.times (b) a / ba.div (b) a% ba.rem (b), a.mod (b) (deprecated) a … Ba.rangeTo (b)

The method of operator overloading can be either an instance method or an extension method.

Let's try to overload the + operator in the above table using the instance method. There are two points to note:

Overloaded methods must be marked with operator

The overloaded method name and parameters must be predefined by Kotlin, such as plus here

Data class Point (val x: Int, val y: Int) {operator fun plus (p: Point): Point {return Point (p.x + x P.P. Y + y)}} / / call val p1 = Point (1,2) val p2 = Point (3,4) println (p1 + p2)

Output:

Point (Xerox 4, YB6)

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

This is the end of this article on "how Java engineers use Kotlin". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report