In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/02 Report--
Hello, World.
Kotlin is a statically typed language that runs on JVM and is 100% interoperable with existing Java code. For most Java developers, the following program should be familiar:
Package com. Bugsnag . Kotlin
Public course App {public static void main (String [] args) {system. Out. Println ("Hello World!" );}}
The following will print "Hello World" in Kotlin:
Fun main (args:Array
< String >) {println ("Hello World!" )}
Some differences are obvious, such as the lack of semicolons and how concise our code is.
Kotlin and Java
To understand Kotlin, let's take a closer look at its functions and how they compare to Java.
No security
We will first explore one of the most useful features of Kotlin-it supports null security. In Java, any object can be null. This means that run-time checks must be added to the entire code library to prevent NullPointerException from crashing, which is often called a billion-dollar error by language designers.
Static class user {string name;}
Public void printUsername (User user) {if (user. Name! = empty) {FOO (user. First name. Length ();}}
In Kotlin, references to objects must be nullable or non-nullable:
Class User (var name:String? ) / / name attribute can be nullclass User (var name:String) / / name attribute cannot be null
If the developer tries to pass an object that can be null to the second class, a compile-time error occurs.
Secure call to operator
The following are familiar to most Java developers. The user parameter can be null, so a run-time check is required to ensure that the NPE is avoided.
Void printUsername (User user) {if (user. GetName ()! = empty) {FOO (user. GetName () length ();} else {foo (null); / / provide a null integer}}
Void foo (integer length) {}
Kotlin can simplify this process through Safe Call operators. If name is not null, its length is passed as a parameter. Otherwise, a null reference is passed.
Fun printUsername (user:User) {FOO (user. Name?. Length) if user.name is empty / / return null}
Fun foo (length:Int? ) {}
Or, if it doesn't make sense to execute code with a value of null, we can use let:
Fun foo (nullableUser:User? ) {nullableUser?. Let {printUsername (nullableUser)} / / only print non-empty user name} fun printUsername (user:User) {} / / User is a non-null reference
Class definition
Compared to Java, the Kotlin class is very concise. The following class defines three fields, getter and setter more than 30 lines!
Class User {final string name; int age = 18; string address
Public User (String name,int age,String address) {this. Name = name; this. Age = age; this. Address = address;}
Public String getName () {returns the name;}
Public int getAge () {regression age;}
Public void setAge (int age) {this. Age = age;}
Public String getAddress () {return address;}
Public void setAddress (String address) {this. Address = address;}}
In Kotlin, we can do the same thing with a single line of code.
Class User (val name:String,var age:Int = 18Ma var address:String? )
Immutable references are also easier. This is just a switch from the var keyword to the problem val.
You may have noticed that for Kotlin, you can provide default values for parameters. This means that Java patterns, such as Builder patterns, can be eliminated from Kotlin. This can also greatly reduce the amount of code required for syntax sugars, such as the method chain in the public API.
Data class
If the main purpose of our class is to save data, such as the JSON payload from API, things will become more concise. In Kotlin, these are called data classes.
Data class User (val name:String,var age:Int = 18Ma var address:String? )
Simply adding the data keyword automatically generates equals (), hashCode (), toString (), and copy () for our class implementation. This kind of equivalent Java implementation is omitted to save the reader's reason and bandwidth cost.
Type inference
Kotlin uses type inference, which further increases its simplicity. Consider this Java class:
Class AbstractSingletonProxyFactoryBean {}
Public void foo () {AbstractSingletonProxyFactoryBean bean = new AbstractSingletonProxyFactoryBean ();}
And the equivalent in Kotlin looks like this:
Class AbstractSingletonProxyFactoryBean
Fun foo () {val bean = AbstractSingletonProxyFactoryBean () / / automatically infer type}
Function
Type inference permeates the entire language. It can be explicit or implicit when needed, as shown in the following two ways to define the same function:
Int add (int a _ line int b) {returns a + b;}
Fun add: Int {/ / explicit return type returns a + b}
The inferred return type of fun add (aVlIntrebjnt) = a + b / /
Attribute
Kotlin Properties is amazing. Consider the following Java class, which uses the accessor method to define a single field:
Class Book {string author
String getAuthor () {return to the author;}
Void setAuthor (String author) {this. Author = author;}}
Book = new book (); book. SetAuthor ("Kurt Vonnegut"); system. Out. Println of the book. GetAuthor ()
By defining a class that declares the author attribute, you can achieve the equivalent functionality in four lines of Kotlin. We will automatically generate our getter and setter:
Class Book (var author:String? ) val book = Book () Book. Author = "Kurt Vonnegut" println (book. Author)
Custom visitors
If getter and setter require custom behavior, you can override the default behavior. For example:
Class Person (var firstName:String,var lastName:String) {
Var fullName:String get () = "${firstName} ${lastName}" set (value) {val split = value. Split (") firstName = split [0] lastName = split [1]}}
If we need to validate fields or restrict them to certain inputs, we can also use supporting fields:
Set (value) {if (Santa Claus). Equal to (value) field = "Oyster HO"}
Interoperability
Another advantage of Kotlin is that it can be called from Java code in the same project, and vice versa.
Public class MyJavaClass {public String authorName
Public boolean isTruthyValue () {return true;}}
The following Kotlin function instantiates a new Java object and accesses its methods and fields using regular Kotlin syntax. This is convenient if you want to dip your toes in water by adding a small amount of Kotlin to your existing Java code base.
Fun main (args:Array
< String >) {val obj = println (OBJ of MyJavaClass (). Println (OBJ) of AUTHORNAME. IsTruthyValue)}
It's also worth mentioning that Kotlin can be decompiled back to Java, so if your team doesn't like the language or encounters technical hurdles, you can migrate back.
Practical method
All Java developers will be very familiar with utilities or helper classes. Static methods will perform some useful operations that are not available in the Java standard library and will be called in the code base:
Class StringUtils {static String sortStringChars (String input) {char [] chars = input. ToCharArray (); array. Sort (characters); return new String (chars);}} StringUtils. SortStringChars ("azbso"); / / returns "abosz"
In Kotlin, extensions allow additional functionality to be added to an existing class without having to extend or wrap the class. For example, the following adds a sortStringChars function String to the class:
Interesting string. SortStringChars (): String {val chars = this. ToCharArray () array. Sort (character) return String (chars)}
Fun main (args:Array
< String >) {"azbso". SortStringChars () / / returns "abosz"}
This makes the grammar easier to read-but be careful. Great power brings great responsibility.
Functional programming
Kotlin fully supports lambda expressions. Limited Java 8 support has just been added to Android, which makes Kotlin's functional programming capabilities particularly popular.
/ / filter a list of val input = listOf ("JK Rowling", "Charles Darwin") val authors = input for all authors whose names begin with "J". Filter {author-> author. StartsWith ("J")} println (author) / / JK Rowling
Direct constructs such as filter and map can also be used on Collections, which is not currently supported on most Android devices.
Fun main (args:Array
< String >) {val input = listOf ("JK Rowling", "Charles Darwin", "") val authors = input Filter {! it. IsEmpty ()} / / remove null values. Map {Author (it)} / / maps a string to an author object. SortedBy {it . Name} / / sort by author name
Println (authors) / / print author in alphabetical order}
Reactive Streams has recently become popular in the Android world, and the RxKotlin library also provides support for Kotlin.
Val cereals = listOf ("Kellogs Coroutines", "Cocoa Pods", "Locky Charms")
grain. ToObservable ()
/ / perform some intensive / complex calculations on background threads
. SubscribeBy (onNext = {println (it) / / observe each grain on the main line and print it})
Kotlin Native and Javascript
Kotlin is primarily targeted at JVM, but can also be converted to Javascript or compiled to native code using the LLVM toolchain. These two goals are still in the early stages of development, but they show great hope for those who want to program in one language throughout the stack.
Kotlin Native is particularly interesting because Swift looks very similar to Kotlin, which means that you may one day use the same native code base in Android and iOS applications.
Another thing worth mentioning is Gradle Script Kotlin, which brings all the benefits of static typing to the existing Gradle DSL and Spring Boot, which provides official support for Kotlin.
Potential downside
So what are the disadvantages of Kotlin?
On Android, application size is a potential problem. Kotlin currently adds about 1Mb to your application size and uses about 7000 methods, although most of them can be stripped off by Proguard. This is not a big deal for traditional Java desktop applications, but for mobile devices with more resource constraints, it can be a deal saboteur for some teams.
Kotlin is not as long as Java, so it is much more difficult to identify bad practices and code smells. Java has 22 years of good practice and linting tools to learn from, while Kotlin does not. For example, extension functions are a very powerful feature, but they can be easily used where classes and abstractions should be used.
A more humane factor is that although Kotlin is very similar to Java, there is always a period of time to learn a new language, which leads to a temporary decline in productivity.
Especially if everyone on the team has become an Java expert in the past decade, they may not be willing to give up and start over in a language they are not familiar with. External customers may not be satisfied with Kotlin because some people think that it has not existed as long as Java and is more unknown.
Why did Kotlin beat Java?
Let's summarize some of the main advantages of Kotlin:
Kotlin is far more concise than Java.
Lambdas and functional constructs have been used out of the box for many years
100% interoperability with existing Java code
Kotlin actually eliminates one of the most common Java errors, the terrible NullPointerException
IntelliJ IDEA provides excellent tool support
The language is written from scratch, so it feels like a language designed by people who program in it every day.
We believe that, for these reasons, Kotlin beat Java on Android. In traditional Java desktop applications, Java 8 is a closer competition because it contains comparable language features such as lambda, streaming, and others. However, we still believe that the simplicity of Kotlin wins in this case.
Suggestions on getting started with Kotlin
It's impossible to summarize programming languages in a blog post, so if you or your team are interested in using Kotlin, our advice is just to give it a try!
The two most common routes are to write unit tests in Kotlin or to convert existing Utils classes to Kotlin. IntelliJ IDEA also provides a convenient shortcut for automatic conversion to migrate existing Java code to Kotlin. While this may not necessarily give you the most familiar Kotlin, it is a good way to learn grammar in a code base that you are familiar with.
The most important thing is to constantly assess whether everyone is satisfied with the level of Kotlin adoption and identify any pain points or hidden traps.
Kotlin is a very good alternative to Java, and if done well, it has the potential to increase developer happiness, reduce the complexity of the code base, and increase business productivity.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.