by Adam Arold
亚当·阿罗德(Adam Arold)
Kotlin是新的Java (Kotlin is the new Java)
If you have been a Java developer for a while now you might be wondering what to learn next. There are a bunch of languages out there which worth a look, like Clojure, Rust or Haskell. But what if you want to learn something with which you can pay the bills but it is not a pain to use? Kotlin is in the sweet spot just where Java used to be and in this article my goal is to explain why.
如果您已经有一段时间成为Java开发人员,那么您可能想知道接下来要学习什么。 有大量值得一看的语言,例如Clojure , Rust或Haskell 。 但是,如果您想学习一些可以付账的东西,但使用起来却不难,该怎么办? Kotlin处在Java曾经的最佳位置,在本文中,我的目标是解释原因。
那么,Kotlin是什么? (So what is Kotlin?)
A home-grown programming language by JetBrains who are the masterminds behind the acclaimed IDEA IDE and a bunch of other stuff.
JetBrains自主开发的一种编程语言,是广受赞誉的IDEA IDE和许多其他东西的策划者。
- A simple and flexible alternative to Java Java的一种简单而灵活的替代方案
- Which interoperates well with existing Java code 可以与现有的Java代码很好地互操作
- Compiles to Java bytecode 编译为Java字节码
- Runs on the JVM 在JVM上运行
- And also compiles to javascript 并且也可以编译成javascript
If you read the docs you can see a bunch of stuff going for it:
如果您阅读文档,则可以看到很多东西:
- It lets you achieve more with less code 它使您可以用更少的代码获得更多收益
- Solve a lot of problems in Java 解决Java中的许多问题
- Helps you keep using the Java ecosystem 帮助您继续使用Java生态系统
- Lets you write front-end and back-end code in the same language 使您可以使用相同的语言编写前端和后端代码
- Gives you 100% Java interoperability 为您提供100%的Java互操作性
- It does well compared to the alternatives (Clojure, Scala) 与其他选择(Clojure,Scala)相比,它做得很好
- Adds only a thin layer of complexity over Java 仅在Java上增加了一层复杂性
Sounds cool, right? Let’s just not drink the Kool-Aid too soon and see some examples how well it fares compared to Java.
听起来不错,对吗? 让我们不要过早喝Kool-Aid,看看一些例子,它与Java相比有多好。
值对象与数据类 (Value objects vs data classes)
What you see here is a POJO with all the boilerplate:
您在这里看到的是带有所有样板的POJO:
Creating value objects is really cumbersome even with the usage of libraries like Lombok. (Lombok needs you to install a plugin into your IDE in order for it to work which might not be an option for all IDEs. It can be worked around with tools like Delombok but it is a hack at best. Read more here) At least IDEA (or Eclipse) gives you a little help with generating a lot of these methods but adding a field and forgetting to modify the equals
method will lead to nasty surprises. Let’s look at the Kotlin equivalent:
即使使用Lombok之类的库,创建值对象也确实很麻烦。 (Lombok需要您在您的IDE中安装一个插件才能正常工作,这可能不是所有IDE的选项。它可以与Delombok之类的工具一起使用,但充其量只是一个技巧。 在这里了解更多)至少IDEA(或Eclipse)为您提供了许多生成这些方法的帮助,但是添加一个字段却忘记修改equals
方法将导致令人讨厌的意外。 让我们看一下Kotlin等效项:
Whoa! That’s quite less typing compared to the Java version. Data classes in Kotlin give you
哇! 与Java版本相比,键入的内容要少得多。 Kotlin中的数据类为您提供
equals
+hashCode
andequals
+hashCode
和toString
in addition totoString
除了getters and setters. You can also
copy
them which effectively creates a new object with some fields overwritten. See here for more information on this topic.吸气剂和二传手。 您也可以
copy
它们,从而有效地创建一个覆盖了某些字段的新对象。 有关此主题的更多信息,请参见此处 。
字符串插值 (String interpolation)
String manipulation in Java is painful. It can be alleviated by using String.format
but it will still remain ugly.
Java中的字符串操作很痛苦。 可以使用String.format
缓解它,但仍然会很丑陋。
Kotlin works around this by adding String interpolation to the mix with which it is a bit simpler to use variables in String literals. You can even call methods from one!
Kotlin通过将String插值添加到混合中来解决此问题,使用String插值可以更简单地使用String文字中的变量。 您甚至可以从一个调用方法!
扩展功能 (Extension functions)
Writing decorators in Java can be tricky and they are not perfect. If you want to write a decorator which can be used with all classes implementing List
you can’t simply use it in your decorator because it would need you to implement a lot of other methods so you have to extend AbstractList
.
用Java编写装饰器可能很棘手,而且并不完美。 如果要编写一个可以与所有实现List
类一起使用的装饰器,则不能在装饰器中简单地使用它,因为它需要您实现许多其他方法,因此必须扩展AbstractList
。
If you need to decorate something which does not provide useful base classes like AbstractList
or is a final
class then you are out of luck. Extension methods come to the rescue!
如果您需要装饰一些无法提供有用的基类(例如AbstractList
或final
类的东西,那么您就不走运了。 扩展方法可助您一臂之力!
This method acts as a decorator for all List
s. Compared to the Java alternative this one-liner is much simpler and it will also work for final
classes. Just try not to abuse them.
此方法充当所有List
的装饰器。 与Java替代方法相比,这种单行代码要简单得多,它也适用于final
类。 只是不要滥用它们。
空安全 (Null safety)
Checking for null
values involves a lot of boolean expressions and a lot of boilerplate. With the advent of Java 8 you can finally work around this with the Optional
class but what if the reference to an Optional
is null
? Yes, you’ll get a NullPointerException
and after 20 years of Java we still don’t know what was null. Take the following example:
检查null
值涉及许多布尔表达式和许多样板。 随着Java 8的出现,您最终可以使用Optional
类解决此问题,但是如果对Optional
的引用为null
怎么办? 是的,您将获得NullPointerException
并且在使用Java 20年之后,我们仍然不知道什么是null。 请看以下示例:
With Kotlin you have several options. If you have to interop with Java projects you can use the null safety operator (?
):
使用Kotlin,您有多种选择。 如果必须与Java项目互操作,则可以使用null安全运算符( ?
):
The code will only run after a ?
if its left operand is not null
. The let
function creates a local binding for the object it was called upon so here it
will point to it.city
. If you don’t have to interop with Java I would suggest doing away with null
s completely:
该代码仅在?
之后运行?
如果其左操作数不为null
。 该let
函数创建一个本地的它被要求使这里的对象绑定it
会指向it.city
。 如果您不必与Java互操作,建议您完全放弃null
:
If there are no null
s involved (no ?
s present) it all becomes a lot more simpler.
如果不涉及null
(不存在?
),则一切将变得更加简单。
类型推断 (Type Inference)
Kotlin supports type inference which means that it can derive types from the context in which they are present. This is like the Java diamond notation &l
t;> but on steroids! Take the following example:
Kotlin支持类型推断,这意味着它可以从存在它们的上下文中派生类型。 这就像Java钻石符号&l
t;>,但在类固醇上! 请看以下示例:
This looks almost the same in Kotlin:
这在Kotlin中几乎相同:
Until you let Kotlin figure out the types of your variables:
直到您让Kotlin弄清楚变量的类型:
or even methods:
甚至方法:
没有检查的例外 (No checked exceptions)
You must have seen this piece of code at least a million times:
您必须至少看过这段代码一百万次:
Old school IO in Java. Note the try with resources block! The same would look like this in Kotlin:
Java的老派IO。 注意try with resources块! 在Kotlin中看起来像这样:
There are a couple of things going on here. First Kotlin does away with checked exceptions. Secondly Kotlin adds use
to any Closeable
object which basically:
这里发生了几件事。 First Kotlin取消了已检查的异常。 其次,Kotlin基本上在任何Closeable
对象中添加了use
:
Executes the given [block] function on this resource and then closes it down correctly whether an exception is thrown or not. (Taken from Kotlin’s documentation)
在此资源上执行给定的[block]函数,然后无论是否引发异常都正确关闭它。 (摘自Kotlin的文档)
What you can also see here is that an extension function (readLines
) is added to the File
class. This pattern is visible throughout Kotlin’s rather small standard library. If you have ever used Guava, Apache Commons or something similar, chances are that you will see common functionality from them added to a JDK class as an extension function. Needless to say this will be good for your health (nerves at least).
您还可以在此处看到将扩展功能( readLines
)添加到File
类。 这种模式在Kotlin相当小的标准库中可见。 如果您曾经使用过Guava,Apache Commons或类似工具,则很有可能会看到它们中的通用功能作为扩展功能添加到了JDK类中。 不用说这对您的健康有益(至少对神经有益)。
Lambda支持 (Lambda support)
Let’s look at the lambda support in Java:
让我们看看Java对lambda的支持:
Since there is no syntax for method parameter types we have to create an interface for it. Note that we could use Function<String, Boole
an> here but it only works for functions with one parameter! There are some interfaces in the JDK to solve this problem but if someone looks at the code they might be puzzled what a BiFu
nction is useful for? Kotlin improves on this a bit:
由于方法参数类型没有语法,因此我们必须为其创建接口。 请注意,我们可以在此处使用Function<String, Boole
an>,但它仅适用于具有一个参数的函数! JDK中有一些接口可以解决此问题,但是如果有人看了代码,可能会感到困惑, hat a BiFu
函数对您有用吗? Kotlin在此方面有所改进:
Kotlin adds a syntax for passing functions as parameters: (ParamType1, ...ParamTypeN) -> ReturnT
ype. And with Kotlin you have method and field references and you can also refer to a method from a concrete object! Using the example above I can refer to the filte
rBy function on a concrete instance like this:
Kotlin添加了将函数作为参数传递的语法: (ParamType1, ...ParamTypeN) -> ReturnT
ype。 使用Kotlin,您可以使用方法和字段引用,还可以从具体对象中引用方法! 使用上面可以参考我到t的例子he filte
在这样一个具体的实例RBY功能:
功能编程 (Functional programming)
Functional programming is all the buzz nowadays and with Java 8 they have released Oracle’s take on the topic: the Stream API. It works like this:
函数式编程如今已成为热门话题,并且使用Java 8,他们发布了Oracle的主题:Stream API。 它是这样的:
The Kotlin equivalent is rather similar, but subtly different:
Kotlin的等效项相当相似,但略有不同:
There is no explicit conversion to streams since all Kotlin collections support it out of the box. Not having to pass a lambda to flatMap
here is a direct consequence of this. Collecting the result is also automatic (no need for Collectors.to*
method calls). We only had to use toSet
here because we want to return a Set
. Otherwise .toSet()
can be omitted.
由于所有Kotlin集合均支持开箱即用,因此无需明确转换为流。 不必在这里将lambda传递给flatMap
是直接的结果。 收集结果也是自动的(不需要Collectors.to*
方法调用)。 我们只需要在这里使用toSet
,因为我们要返回Set
。 否则,可以省略.toSet()
。
Kotlin-java互操作 (Kotlin-java interoperation)
Well this can be a dealbreaker for most people but JetBrains got this right:
好吧,对于大多数人来说,这可能是一个大难题,但是JetBrains做到了这一点:
The interop is seamless and painless. Java and Kotlin can live together in the same project and Kotlin supplies a set of annotations (like @JvmStatic
here) so Kotlin code can be called from Java without any fuss. Check here for further information on this topic.
互操作是无缝且无痛苦的。 Java和Kotlin可以一起生活在同一个项目中,并且Kotlin提供了一组注释(例如此处的@JvmStatic
),因此可以从Java调用Kotlin代码,而不必大惊小怪。 在此处查看有关此主题的更多信息。
As you might have seen from these examples Kotlin takes the good ideas from Java, improves upon them and tries to keep the WTF/minute counter to a minimum. The recent news about Google making Kotlin one of the supported languages on Android also underpins this.
正如您从这些示例中可能已经看到的那样,Kotlin采纳了Java的优秀思想,对其进行了改进,并试图将WTF /分钟计数器保持在最低水平。 关于Google的最新消息也使Kotlin成为Android上受支持的语言之一。
事情要告诉你的老板 (Things to tell your boss)
So if you want to give it a try here are some pointers which will help you when negotiating with your boss and teammates:
因此,如果您想尝试一下,这里有一些建议可以帮助您与老板和队友进行谈判:
- Kotlin comes from industry, not academia. It solves problems faced by working programmers today. Kotlin来自行业,而不是学术界。 它解决了当今工作的程序员所面临的问题。
- It is free and Open Source 它是免费和开源的
- It comes with a useful Java to Kotlin converter tool 它带有有用的Java到Kotlin转换工具
You can mix Kotlin and Java with zero effort
您可以毫不费力混合Kotlin和Java
You can use all existing java tools/frameworks
您可以使用所有现有的Java工具/框架
- Kotlin is supported by the best IDE on the market (with a free version) Kotlin受到市场上最好的IDE的支持(带有免费版本)
- It is easy to read, even non-Kotlin programmers can review your code 易于阅读,即使非Kotlin程序员也可以查看您的代码
You don’t need to commit your project to Kotlin: you can start by writing your tests in it
您无需将项目提交给Kotlin: 您可以从在其中编写测试开始
- JetBrains is not likely to abandon Kotlin because it drives their sales JetBrains不太可能放弃Kotlin,因为它推动了销售
Kotlin has a vibrant community and even you can easily contribute to Kotlin and suggest new features using KEEP
Kotlin有一个充满活力的社区,甚至您也可以使用KEEP轻松地为Kotlin做出贡献并提出新功能
So does it live up to the hype? Only you can tell. Here are a few pointers where you can start:
那么,它可以辜负炒作吗? 只有你能说出来。 这里有一些可以开始的指针:
Kotlin Blog <– this will keep you up to date
Kotlin博客 <–这将使您保持最新状态
Awesome Kotlin <– Curated list of Kotlin resources and libraries
Awesome Kotlin <– Kotlin资源和图书馆的精选清单
You can also check the source of the examples presented in this article here.
您还可以在此处查看本文介绍的示例的来源。
Originally published at the-cogitator.com on May 19, 2017.
最初于2017年5月19日在the-cogitator.com上发布。
翻译自: https://www.freecodecamp.org/news/kotlin-is-the-new-java-16b35c5f54a2/