kotlin和java語言
It has been several years since Kotlin came out, and it has been doing well. Since it was created specifically to replace Java, Kotlin has naturally been compared with Java in many respects.
自Kotlin問世以來已經有好幾年了,而且一切都很好。 自從Kotlin專門為替代Java而創建以來,自然在很多方面都與Java進行了比較。
To help you decide which of the two languages you should pick up, I will compare some of the main features of each language so you can choose the one you want to learn.
為了幫助您確定應該選擇兩種語言中的哪一種,我將比較每種語言的一些主要功能,以便您可以選擇想要學習的一種。
These are the 8 points I'll discuss in this article:
這些是我將在本文中討論的8點:
- Syntax 句法
- Lambda Expressions Lambda表達式
- Null Handling 空處理
- Model Classes 模型類
- Global Variables 全局變量
- Concurrency 并發
- Extension Functions 擴展功能
- Community 社區
語法比較 (Syntax comparison)
To start it all let's do some basic syntax comparison. Many of you who are reading this might already have some knowledge about Java and/or Kotlin, but I will give out a basic example below so we can compare them directly:
首先,讓我們做一些基本的語法比較。 許多正在閱讀本文的人可能已經對Java和/或Kotlin有所了解,但是我將在下面給出一個基本示例,以便我們直接進行比較:
Java (Java)
public class HelloClass { public void FullName(String firstName, String lastName) {String fullName = firstName + " " + lastName;System.out.println("My name is : " + fullName); } public void Age() { int age = 21;System.out.println("My age is : " + age); } public static void main(String args[]) { HelloClass hello = new HelloClass(); hello.FullName("John","Doe");hello.Age();}
}
Kotlin (Kotlin)
class NameClass {fun FullName(firstName: String, lastName:String) {var fullName = "$firstName $lastName"println("My Name is : $fullName")}
}fun Age() {var age : Intage = 21println("My age is: $age")
}fun main(args: Array<String>) {NameClass().FullName("John","Doe")Age()
}
The feel of the code isn't that different aside from some small syntax changes in the methods and classes.
除了在方法和類中進行一些小的語法更改外,代碼的感覺沒有什么不同。
But the real difference here is that Kotlin supports type inference where the variable type does not need to be declared. Also we don't need semicolons ( ;
) anymore.
但是真正的區別在于Kotlin支持類型推斷,不需要聲明變量類型。 另外,我們不再需要分號( ;
)。
We can also note that Kotlin does not strictly enforce OOP like Java where everything must be contained inside a class. Take a look at fun Age
and fun main
in the example where it is not contained inside any class.
我們還可以注意到Kotlin并不像Java那樣嚴格執行OOP,因為Java必須將所有內容都包含在一個類中。 看一下示例中沒有包含的fun Age
和fun main
。
Kotlin also typically has fewer lines of codes, whereas Java adheres more to a traditional approach of making everything verbose.
Kotlin通常還具有較少的代碼行,而Java則更加遵循使一切變得冗長的傳統方法。
One advantage of Kotlin over Java is Kotlin's flexibility – it can choose to do everything in the traditional OOP approach or it can go a different way.
Kotlin相對于Java的一個優勢是Kotlin的靈活性–它可以選擇以傳統的OOP方法進行所有操作,也可以采用其他方法。
Lambda表達式 (Lambda Expressions)
If we are talking about Java and Kotlin, of course we have to talk about the famous lambda expression. Kotlin has native Lambda support (and always has), while lambda was first introduced in Java 8.
如果我們要談論Java和Kotlin,那么我們當然必須談論著名的lambda表達式。 Kotlin具有本地Lambda支持(并且一直有),而Lambda最初是在Java 8中引入的。
Let's see how they both look.
讓我們看看它們的外觀。
Java (Java)
//syntaxes
parameter -> expression
(parameter1, parameter2) -> { code }//sample usage
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(9);
numbers.forEach( (n) -> { System.out.println(n); } );
Kotlin (Kotlin)
//syntax
{ parameter1, parameter2 -> code }//sample usage
max(strings, { a, b -> a.length < b.length })
In Java, the parentheses are more lenient: if only one parameter exists, there is no need for parenthesis. But in Kotlin brackets are always required. Overall, however, there are not many differences aside from syntax.
在Java中,括號更為寬松:如果僅存在一個參數,則無需括號。 但在Kotlin中,始終需要使用括號。 總體而言,除了語法外,沒有太多區別。
In my opinion, lambda functions won't be used much aside from using them as callback methods. Even though lambda functions have so many more uses, readability issues make it less desirable. They'll make your code shorter, but figuring out the code later will be much more difficult.
我認為,除了將lambda函數用作回調方法外,它不會被大量使用。 即使lambda函數有更多用途,但可讀性問題仍使它不太理想。 它們會使您的代碼更短,但是以后弄清楚代碼將更加困難。
It's just a matter of preference, but I think it's helpful that Kotlin enforces the mandatory brackets to help with readability.
這只是一個偏好問題,但是我認為Kotlin強制使用必需的括號來幫助提高可讀性是有幫助的。
空處理 (Null Handling)
In an object oriented language, null type values have always been an issue. This issue comes in the form of a Null Pointer Exception (NPE) when you're trying to use the contents of a null value.
在面向對象的語言中,空類型值始終是一個問題。 當您嘗試使用空值的內容時,此問題以空指針異常(NPE)的形式出現。
As NPEs have always been an issue, both Java and Kotlin have their own way of handling null objects, as I will show below.
由于NPE一直是一個問題,因此Java和Kotlin都有其處理空對象的方式,這將在下面顯示。
Java (Java)
Object object = objServ.getObject();//traditional approach of null checking
if(object!=null){System.out.println(object.getValue());
}//Optional was introduced in Java 8 to further help with null values//Optional nullable will allow null object
Optional<Object> objectOptional = Optional.ofNullable(objServ.getObject());//Optional.of - throws NullPointerException if passed parameter is null
Optional<Object> objectNotNull = Optional.of(anotherObj);if(objectOptional.isPresent()){Object object = objectOptional.get();System.out.println(object.getValue());
}System.out.println(objectNotNull.getValue());
Kotlin (Kotlin )
//Kotlin uses null safety mechanism
var a: String = "abc" // Regular initialization means non-null by default
a = null // compilation error//allowing null only if it is set Nullable
var b: String? = "abc" // can be set null
b = null // ok
print(b)
For as long as I can remember, Java has been using traditional null checking which is prone to human error. Then Java 8 came out with optional classes which allow for more robust null checking, especially from the API/Server side.
就我所知,Java一直在使用傳統的null檢查,這很容易發生人為錯誤。 然后,Java 8推出了可選類,這些類允許進行更健壯的null檢查,尤其是從API / Server方面。
Kotlin, on the other hand, provides null safety variables where the variable must be nullable if the value can be null.
另一方面,Kotlin提供了空安全變量,如果該值可以為空,則該變量必須為空。
I haven't really used optional class yet, but the mechanism and purpose seems pretty similar to Kotlin's null safety. Both help you identify which variable can be null and help you make sure the correct check is implemented.
我還沒有真正使用可選類,但是機制和目的似乎與Kotlin的null安全性非常相似。 既可以幫助您確定哪個變量可以為null,又可以確保執行正確的檢查。
Sometimes in code there might be just too many variables lying around and too many to check. But adding checking everywhere makes our code base ugly, and nobody likes that, right? ?
有時,在代碼中可能存在太多變量并且需要檢查的變量太多。 但是到處添加檢查會使我們的代碼基礎很難看,沒有人喜歡它,對吧?
In my opinion, though, using Java's optional feels a bit messy because of the amount of code that needs to be added for the checks. Meanwhile in Kotlin, you can just add a small amount of code to do null checking for you.
但是,在我看來,使用Java的可選方法會感到有些混亂,因為需要為檢查添加大量的代碼。 同時,在Kotlin中,您只需添加少量代碼即可為您執行null檢查。
型號類別 (Model Class)
Some people might also refer to this as the Entity class. Below you can see how both classes are used as model classes in each language.
某些人也可能將此稱為Entity類。 在下面,您可以看到兩種類如何在每種語言中用作模型類。
Java (Java)
public class Student {private String name;private Integer age;// Default constructorpublic Student() { }public void setName(String name) {this.name = name;}public String getName() {return name;}public void setAge(Integer age) {this.age = age;}public Integer getAge() {return age;}
}
Kotlin (Kotlin)
//Kotlin data class
data class Student(var name: String = "", var age: Int = 0)//Usage
var student: Student = Student("John Doe", 21)
In Java, properties are declared as private, following the practice of encapsulation. When accessing these properties, Java uses Getters and Setters, along with the isEqual or toString methods when needed.
在Java中,遵循封裝實踐,將屬性聲明為私有。 訪問這些屬性時,Java將在需要時使用Getter和Setter以及isEqual或toString方法。
On the Kotlin side, data classes are introduced for the special purpose of model classes. Data classes allow properties to be directly accessed. They also provide several in-built utility methods such as equals(), toString() and copy().
在Kotlin方面,出于模型類的特殊目的引入了數據類。 數據類允許直接訪問屬性。 它們還提供了幾種內置實用程序方法,例如equals(),toString()和copy()。
For me, data classes are one of the best things Kotlin offers. They aim to reduce the amount of the boilerplate code you need for regular model classes, and they do a really good job of that.
對我來說,數據類是Kotlin提供的最好的東西之一。 它們的目的是減少常規模型類所需的樣板代碼量,并且它們確實做得很好。
全局變量 (Global Variables)
Sometimes your code might need a variable needs to be accessed everywhere in your code base. This is what global variables are used for. Kotlin and Java each have their own ways of handling this.
有時,您的代碼可能需要在代碼庫中的任何位置訪問變量。 這就是全局變量的用途。 Kotlin和Java都有各自的處理方式。
Java (Java)
public class SomeClass {public static int globalNumber = 10;
}//can be called without initializing the class
SomeClass.globalNumber;
Kotlin (Kotlin)
class SomeClass {companion object {val globalNumber = 10}
}//called exactly the same like usual
SomeClass.globalNumber
Some of you might already be familiar with the static keyword here since it's also used in some other language like C++. It's initialized at the start of a program's execution, and is used by Java to provide global variables since it is not contained as an Object. This means it can be accessed anywhere without initializing the class as an object.
你們中的某些人可能已經在這里熟悉static關鍵字,因為它也在其他一些語言(例如C ++)中使用。 它在程序執行開始時進行了初始化,并且由于不包含在Object中,因此Java用于提供全局變量。 這意味著無需將類初始化為對象就可以在任何地方訪問它。
Kotlin is using quite a different approach here: it removes the static keyword and replaces it with a companion object which is pretty similar to a singleton. It let's you implement fancy features such as extensions and interfacing.
Kotlin在這里使用了完全不同的方法:它刪除了static關鍵字,并將其替換為與單例非常相似的伴隨對象 。 它使您可以實現擴展和接口等高級功能。
The lack of the static keyword in Kotlin was actually quite surprising for me. You could argue that using the static keyword might not be a good practice because of its nature and because it's difficult to test. And sure, the Kotlin companion object can easily replace it.
實際上,在Kotlin中缺少static關鍵字令我感到非常驚訝。 您可能會爭辯說使用static關鍵字可能不是一個好的做法,因為它的性質和測試難度很大。 當然,Kotlin隨行對象可以輕松替換它。
Even then, using static for global variable should be simple enough. If we are careful with it and don't make it a habit of making every single thing global, we should be good.
即使這樣,將static用于全局變量也應該足夠簡單。 如果我們謹慎對待它,而不是讓它成為使每件事都全球化的習慣,那我們應該很好。
The companion object might also give us some flexibility with interfacing and such, but how often will we ever be interfacing singleton classes?
伴隨對象還可能使我們在接口等方面具有一定的靈活性,但是我們將多久進行一次單例類接口呢?
I think static keywords help us keep things short and clean for global variables.
我認為靜態關鍵字有助于我們使全局變量簡短明了。
并發 (Concurrency)
Nowadays, concurrency is a hot topic. Sometimes the ability of a programming language to run several jobs concurrently might help you decide if that will be your language of choice.
如今,并發是一個熱門話題。 有時,一種編程語言可以同時運行多個作業的能力可能會幫助您確定這是否是您選擇的語言。
Let's take a look at how both languages approach this.
讓我們看一下兩種語言如何實現這一目標。
Java (Java)
// Java code for thread creation by extending
// the Thread class
class MultithreadingDemo extends Thread
{ public void run() { try{ // Displaying the thread that is running System.out.println ("Thread " + Thread.currentThread().getId() + " is running"); } catch (Exception e) { // Throwing an exception System.out.println ("Exception is caught"); } }
} // Main Class
public class Multithread
{ public static void main(String[] args) { int n = 8; // Number of threads for (int i=0; i<n; i++) { MultithreadingDemo object = new MultithreadingDemo(); object.start(); } }
}
Kotlin (Kotlin)
for (i in 1..1000)GlobalScope.launch {println(i)}
Java mostly uses threads to support concurrency. In Java, making a thread requires you to make a class that extends to the in-built Java thread class. The rest of its usage should be pretty straightforward.
Java主要使用線程來支持并發。 在Java中,創建線程要求您創建一個擴展到內置Java線程類的類。 其余的用法應該非常簡單。
While threads are also available in Kotlin, you should instead use its coroutines. Coroutines are basically light-weight threads that excel in short non-blocking tasks.
雖然Kotlin中也提供了線程,但是您應該改用它的協程 。 協程基本上是輕量級線程,在短時間的非阻塞任務中表現出色。
Concurrency has always been a hard concept to grasp (and also, to test). Threading has been used for a long time and some people might already been comfortable with that.
并發一直是一個很難理解(以及測試)的概念。 線程已經使用了很長時間,有些人可能已經對此感到滿意。
Coroutines have become more popular lately with languages like Kotlin and Go (Go similarly has goroutines). The concept differs slightly from traditional threads – coroutines are sequential while threads can work in parallel.
協程最近在諸如Kotlin和Go之類的語言中變得更加流行(Go同樣具有goroutines)。 該概念與傳統線程略有不同- 協程是順序的,而線程可以并行工作 。
Trying out coroutines, though, should be pretty easy since Kotlin does a very good job explaining them in their docs. ?And one bonus for Kotlin over Java is the amount of boilerplate code that can be removed in Kotlin.
但是,嘗試協程應該很容易,因為Kotlin在他們的文檔中很好地解釋了協程。 Kotlin優于Java的一個好處是可以在Kotlin中刪除的樣板代碼數量。
擴展功能 (Extension Functions)
You might be wondering why I'm bringing these up since Java itself doesn't even have this feature.
您可能想知道為什么我要提出這些建議,因為Java本身甚至沒有此功能。
But I can't help but mention it, because extension functions are a very useful feature that was introduced in Kotlin.
但是我不得不提,因為擴展功能是Kotlin中引入的一項非常有用的功能。
fun Int.plusOne(): Int {return this + 1
}fun main(args: Array<String>) {var number = 1var result = number.plusOne()println("Result is: $result")
}
They allow a class to have new functionality without extending it into the class or using any of the fancy Design Patterns. ?It even lets you to add functionality to Kotlin variable classes.
它們允許類具有新功能,而無需將其擴展到類中或使用任何奇特的設計模式。 它甚至允許您向Kotlin變量類添加功能。
You can practically say goodbye to those lib method that need you to pass everything inside your parameters.
實際上,您可以對那些需要在參數中傳遞所有內容的lib方法說再見。
社區 (Community)
Last but not least, let's talk about something non-technical. First, let's take a look at this survey showing top commonly used programming languages in 2020.
最后但并非最不重要的一點,讓我們談談非技術性的東西。 首先,讓我們看一下這份調查,該調查顯示了2020年最常用的編程語言。
We can see that Java is one of the most commonly used languages. And while Kotlin is still rising a lot in popularity, the Java community still remains several times larger than Kotlin and it will probably not change anytime soon.
我們可以看到Java是最常用的語言之一。 盡管Kotlin仍在流行,但Java社區的規模仍然是Kotlin的幾倍,并且它可能不會很快改變。
So what does that matter then? Actually it does matter, a lot. With the amount of people in the Java community, it's much easier to find references and get help when you need it, both on the Internet and in the real world.
那那有什么關系呢? 實際上,這確實很重要。 由于Java社區中的人員眾多,因此在Internet和現實世界中,在需要時可以更輕松地找到參考并獲得幫助。
Many companies are also still using Java as their base and it might not change anytime soon even with Kotlin's interoperability with Java. And usually, doing a migration just doesn't serve any business purpose unless the company has really really important reasons for it.
許多公司仍以Java為基礎,即使Kotlin與Java具有互操作性,它也可能不會很快改變。 通常,除非公司有確實非常重要的理由,否則進行遷移根本不會達到任何業務目的。
結語 (Wrapping up)
For those just scrolling for the summary, here's what we discussed:
對于僅滾動查看摘要的人員,這是我們討論的內容:
- Syntax: the patterns don't differ that much aside from slight syntax differences, but Kotlin is more flexible in several aspects. 語法:除了語法上的細微差異外,這些模式沒有太大差異,但是Kotlin在多個方面都更加靈活。
- Lambda Expressions: the syntax is almost the same, but Kotlin uses curly brackets to help readability. Lambda表達式:語法幾乎相同,但Kotlin使用大括號來提高可讀性。
- Null Handling: Java uses a class to help with null handling while Kotlin uses in-built null safety variables. 空處理:Java使用一個類來幫助進行空處理,而Kotlin使用內置的空安全變量。
- Model Classes: Java uses classes with private variables and setter / getter while Kotlin supports it with data classes. 模型類:Java使用帶有私有變量和setter / getter的類,而Kotlin通過數據類支持它。
- Global Variables: Java uses the static keyword while Kotlin uses something akin to sub-classes. 全局變量:Java使用static關鍵字,而Kotlin使用類似于子類的東西。
- Concurrency: Java uses multi-threading whereas Kotlin uses coroutines (which are generally lighter). 并發性:Java使用多線程,而Kotlin使用協程(通常比較輕)。
- Extension Functions: a new feature introduced by Kotlin to easily give functionality into classes without extending it. 擴展功能:Kotlin引入的一項新功能,可以在不擴展功能的情況下輕松地將其賦予類。
- Community: Java still reigns supreme in the community aspect which makes it easier to learn and get help. 社區:Java在社區方面仍然占據主導地位,這使得學習和獲得幫助變得更加容易。
There are many more features we could compare between Java and Kotlin. But what I've discussed here are, in my opinion, some of the most important.
我們可以在Java和Kotlin之間進行比較的更多功能。 但是,我認為這里討論的是一些最重要的內容。
I think Kotlin is well worth picking up at the moment. From the development side it helps you remove long boilerplate code and keep everything clean and short. If you are already a Java programmer, learning Kotlin shouldn't be too hard and it's okay to take your time at it.
我認為Kotlin目前非常值得一游。 從開發的角度來看,它可以幫助您刪除冗長的樣板代碼,并使所有內容保持簡潔。 如果您已經是Java程序員,那么學習Kotlin也不應該太困難,可以花些時間在上面。
Thanks for reading! I hope that this article will help you decide which programming language you should pick, Java or Kotlin. And for anything that I'm missing, feel free to leave feedback for me as it will be very much appreciated.
謝謝閱讀! 我希望本文將幫助您確定應該選擇哪種編程語言,Java還是Kotlin。 對于我所缺少的任何內容,請隨時給我留下反饋,我們將不勝感激。
翻譯自: https://www.freecodecamp.org/news/kotlin-vs-java-which-language-to-learn-in-2020/
kotlin和java語言