kotlin功能我最想念Java– Kotlin vs Java

让我们写一篇涵盖“Kotlin vs Java”主题的文章 - 我想告诉你哪个kotlin功能我错过了返回java的大多数。

我作为Java Dev的生活

虽然我是一个大的 支持者kotlin. 编程语言,我仍然每天为我的雇主做很多Java编程。由于我意识到Kotlin的伟大功能,我经常与Java挣扎,因为它有一些“陷阱”,需要额外的样板并错过许多功能。
在这篇文章中,我想描述在Java中编码时最想念的Kotlin功能。

new 和 Semicolon

Ever since I'm doing Kotlin, there are two things I always forget when coding in Java: the new keyword for constructor invocations and the annoying ; to complete statements. Kotlin doesn't have new 和 even semicolons are optional. I really appreciate this decision because it reduces the "句法噪声“。

数据类

In Kotlin, data classes are used for simple data containers, representing JSON objects or returning compound objects from functions amongst other use cases. Of course, Java doesn't support this special type of classes yet. As a result, I often have to implement my own data class, which means a lot of boilerplate in Java.

One special use case is compound objects returned from functions. For example, let's imagine a function that needs to return two objects. In Kotlin we could use a data class, or simpler, a Pair directly. In Java, I tend to create a 值对象,这是一个具有若干最终字段的类,每个类别通过构造函数实例化。类似于Kotlin,我不实施 过时保居者, but use the class's fields directly as public properties. Unfortunately, this is not what we learned as best practice and most Java code style checkers will complain about it. I do not see any encapsulation issues here and it's the least verbose approach in Java. The following shows such a compound object, the inner class Multi. In Kotlin this would be a one-liner.

public class MultiReturn {

    公共静态void main(String [] args){
        new MultiReturn().useMulti();
    }

    public void useMulti() {
        Multi multi = helper();
        System.out.println("Multi with " + multi.count + " and " + multi.name);
    }

    private Multi helper() {
        return new Multi(2, "test");
    }
    
    private static class Multi {
        private final int count;
        private final String name;

        public Multi(int count, String name) {
            this.count = count;
            this.name = name;
        }
    }
}

本地功能

In many situations, we tend to create private methods that are only used inside another single method in order to make this one more readable. In Kotlin, we can use local functions, i.e. functions inside functions (inside functions...), which enables some kind of scope. For me, this is a much cleaner approach, because the function is only accessible inside the function that actually uses the local one. Let's look at an example.


fun deployVerticles() {

    fun deploy(verticleClassName: String) {
        vertx.deployVerticle(verticleClassName, opt, { deploy ->
            LOG.info("$verticleClassName has been deployed? ${deploy.succeeded()}")
        })
    }

    deploy("ServiceVerticle")
    deploy("WebVerticle")
}

它从样品中取出 Vert.x. 应用程序并定义一个本地功能,然后重复使用两次。简化代码的好方法。

单个表达式功能

We can create single expression functions in Kotlin, i.e. functions without an actual body. Whenever a function contains only a single expression, it can be placed after a = sign following the function declaration:


fun trueOrFalse() = Random().nextBoolean()

In Java, on the other hand, we always have to use a function body enclosed in {}, which ranges over at least three lines. This is also "句法噪声" I don't want to see anymore. To be fair, Java 1.8 makes it possible to define lambdas which can also solve this, less readable though (Can also be applied to local functions):


public class SingleExpFun {

    private BooleanSupplier trueOrFalse = new Random()::nextBoolean;

    private boolean getNext(){
        return trueOrFalse.getAsBoolean();
    }
}

默认参数

Java的一个非常讨厌的部分是方法必须过载的方式。让我们看看一个例子:

public class Overloade
    公共静态void main(String [] args){
        overloader o = new overloader();
        o.testwithoutprint(2);
        o.test(2);
    }

    public void test(int a, boolean printToConsole) {
        if (printToConsole) System.out.println("int a: " + a);
    }

    public void testWithoutPrint(int a) {
        test(a, false);
    }

    public void test(int a) {
        test(a, true);
    }

}

We can see a class with a method test(int, boolean) that is overloaded for the default case and also a convenience method is available. For more complex examples, it can lead to a lot of redundant code, which is simpler in Kotlin by using default parameters.


fun test(a: Int, printToConsole: Boolean = true) {
    if (printToConsole) println("int a: " + a)
}

fun testWithoutPrint(a: Int) = test(a, false)

fun main(args: Array) {
    testWithoutPrint(2)
    test(2)
}

Calling multiple methods on an object instance (with)

Obviously, Kotlin is more functional than Java. It makes use of higher-order functions in incredibly many situations and provides many standard library functions that can be used as such. One of my favorites is with, which I miss a lot whenever I can't use Kotlin. The with function can be used to create scopes that actually increase the readability of code. It's always useful when you sequentially call multiple functions on a single object.


class Turtle {
    fun penDown()
    fun penUp()
    fun turn(degrees: Double)
    fun forward(pixels: Double)
}

with(Turtle()) {
    penDown()
    for(i in 1..4) {
        forward(100.0)
        turn(90.0)
    }
    penUp()
}

伟大的事情是使用 Lambdas与接收器,你可以在我的一个中阅读 帖子.

零安全

Whenever I work with nullable types since the time I started with Kotlin, I actually miss the type system's tools to prevent null-related errors. Kotlin did a very good job by distinguishing nullable types from not-nullable ones. If you strictly make use of these tools, there is no chance you'll ever see a NullpointerException at runtime.

lambdas和收集处理

kotlin. places a lot of value on its lambdas. As shown in the with example earlier, there's special syntax available for lambdas that makes its usage even more powerful. I want to underline that the way functions and especially lambdas are treated in the language makes it dramatically superior to Java. Let's see a simple example of Java's Streams, which were introduced along with lambdas in Java 1.8:

List list = people.stream().map(Person::getName).collect(Collectors.toList());

It's a rather simple example of a Stream that is used to get a list of names from a list of persons. Compared to what we did before 1.8, this is awesome. Still, it's too noisy compared to a 真正的功能 KOTLIN追求的方法:

val list = people.map { it.name }

或者又一个例子,其中雇员的薪金总结到总金额:

int total = employees.stream()
                      .collect(Collectors.summingInt(Employee::getSalary)));

kotlin.非常简单:

val total = employees.sumBy { it.salary }

kotlin.的例子显示它有多简单 能够 是。 Java不是一种功能语言,并且很难尝试采用Lambdas和Stream等功能功能,因为我们可以轻松地观察片段。如果你经历了Kotlin的美丽,它真的很糟糕。熟悉Intellij后,您是否曾尝试使用Eclipse?你知道我的意思。

包起来

在这篇短篇小说中,我向你介绍了我的顶级Kotlin功能我总是在Java编码时想念。这只是一系列的东西,希望很快就能找到爪哇语。但要诚实地,没有理由始终等待Java,当已经有一种更甜的语言......我想指出,从Kotlin开始真正让我成为一个更好的程序员,因为我开始想知道某些功能在这两种语言中也尝试通过查找不同的方式来查找不同的方法来找到java中的kotlin专用事物。

我对最喜欢的功能感兴趣,请随时发表评论。
此外,如果你愿意,请看看我的 推特 如果您对更多Kotlin的东西感兴趣,请遵循账户,谢谢。

如果您想了解更多关于Kotlin的美丽功能,我推荐这本书 kotlin在行动中 和我的 其他文章 to you.

15 thoughts on “kotlin功能我最想念Java– Kotlin vs Java

发表评论

您的电子邮件地址不会被公开。 必需的地方已做标记 *