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 ExpressionsLambda表达式
  • 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 Agefun 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语言

kotlin和java语言_Kotlin VS Java – 2020年您应该学习哪种编程语言?相关推荐

  1. [JAVA_开课吧资源]第一周 Java语言概述、Java语言基础

    主题一 Java语言概述 » JDK介绍及其基本组件 Sun公司利用Java开发工具箱(Java Development Toolkit ,JDK)发布Java的各个版本.JDK由开发和测试Java程 ...

  2. java语言概述、java语言特性、java语言发展史、java语言作用

    Java介绍: Java语言概述: Java语言是由美国Sun(Stanford University Network)斯坦福网络公司的java语言之父–詹姆斯·高斯林,在1995年推出的高级的编程语 ...

  3. Java语言的介绍,Java环境的配置以及Java编译器的安装

    Java语言的介绍,Java环境的配置以及Java编译器的安装 文章目录 Java语言的介绍,Java环境的配置以及Java编译器的安装 Java 简介 主要特性 关于语言的选择 Python Jav ...

  4. java获取随机数方法_《Java语言程序设计》Java获取随机数方法

    <Java语言程序设计>Java获取随机数方法 在Java中我们可以使用java.util.Random类来产生一个随机数发生器.它有两种形式的构造函数,分别是Random()和Rando ...

  5. Java语言基础(Java自我进阶笔记二)

    Java语言基础(Java自我进阶笔记二) 一. 什么是Java 的主类结构? 1. #mermaid-svg-xWTL2A8kDyyRPexH .label{font-family:'trebuch ...

  6. 您应该在2020年首先学习哪种编程语言? ɐʌɐɾdıɹɔsɐʌɐɾ:ɹǝʍsuɐ

    Most people's journey toward learning to program starts with a single late-night Google search. 大多数人 ...

  7. kotlin和java差别_Kotlin和Java的常用方法的区别总结

    一.kotlin和java的常用语法区别 1).类.public class.public final class java 1 2public final class User{ } 1 2publ ...

  8. enum java 比较_Kotlin与Java比较:枚举类

    前言 Kotlin作为JVM系的语言,起源于Java又不同于Java.通过在语言层面比较两者的区别,可以使得开发者能够快速学习,融会贯通. 枚举使用场景 使用枚举的场景非常明确,即只要一个类的对象是有 ...

  9. day01--java基础编程:计算机基础知识 ,java语言概述,java开发环境搭建,eclipse概述,创建简单java项目,JDK JRE JVM的关系,java开发中的命名规范,编程风格

    1 Day01–Java开发环境+HelloWorld 1.1 计算机基础知识 资料下载网址:刘沛霞 18600949004 code.tarena.com.cn tarenacode code_20 ...

最新文章

  1. Linux系统配置交换分区
  2. Hi3516A开发-- 常见问题FAQs
  3. php 实现二叉树的最大深度_PHP 实现二叉树
  4. Java怎么去最高分最低分,深入java虚拟机:原子操作ParkEvent和Parker
  5. (转)C#开发微信门户及应用(2)--微信消息的处理和应答
  6. ansys 内聚力模型_《ANSYS Workbench有限元分析实例详解(静力学)》,9787115446312
  7. JavaScript入门→HTML引用JS、变量、表达式操作符、数组Array数组对象、选择结构循环结构、函数、JavaScript与JAVA区别
  8. python调用excel的宏_配置Office Excel运行Python宏脚本
  9. blast 数据库说明
  10. import mysql data to solr4.2.0
  11. 【完结】囚生CYの备忘录(20221121-20230123)
  12. 在线使用ChatGPT,国内手机号也可以注册。
  13. 微信小程序 15 个人中心页
  14. 谷歌地球out了,谷歌火星来了!
  15. 微信小程序——设置tabBar
  16. OKHttp 可能你从来没用过这样的拦截器
  17. C/C++:实现精灵游戏
  18. 谷歌账户无法添加_如何将多个Google帐户添加到Google Home
  19. 信息学奥赛入门资源推荐
  20. 小程序的营销推广拓客方式

热门文章

  1. 服务器之select
  2. 04-树4 是否同一棵二叉搜索树 (25 分)
  3. 1074. Reversing Linked List (25)
  4. 《UNIX环境高级编程》目录
  5. Java进阶之光!mysql创建用户并授权建表
  6. 80后程序员月薪30K+感慨中年危机,面试必问!
  7. 微信计步器怎么不计步_难以关闭的微信朋友圈广告
  8. [TimLinux] Python 迭代器(iterator)和生成器(generator)
  9. 网络编程 socket介绍
  10. qml: C++调用qml函数