JavaRush /Java Blog /Random EN /Is there a difference between Kotlin and Java?
Paul Soia
Level 26
Kiyv

Is there a difference between Kotlin and Java?

Published in the Random EN group
Hi all. I want to tell a few basic things about the Kotlin language, which will be useful for beginners. It so happened that now it will be difficult to get into android development with only one language - most new projects start to be written in Kotlin, most of the finished projects are written in Java. Is there a difference between Kotlin and Java?  - 1At the moment I have 4 projects at work: two in Kotlin and two in Java (one large main and three small ones, for internal use). When the company decided to write new projects in Kotlin, this decision seemed strange to me. Why mix different languages? Let someone else write to themselves in Kotlin, why do we need it? But there was no way out, so I decided to try out a new language and began to study it. The first code, of course, was completely written in the Java style, which added more confusion: why do I need a new language? But as I used it, I found more and more advantages, and now (I have been writing in Kotlin for almost 2 years) I can say that Kotlin is more convenient in android development. I want to show some nuances that will not be obvious to someone who decides to start learning Kotlin after Java. Let me also remind you that Android uses Java 8,Variables : Java:
Int a = 1;
String s = "test";
Kotlin:
val a = 1
var b = 2
val c: Int
val d = "test"
There are two types of variables in Kotlin: val (read-only) and var (read-write). It is recommended to use val wherever possible. It is not necessary to declare the type of a variable if the variable has already been initialized. The second is if/else, switch statements : How often do you use this chain of statements in Java:
if (вариант 1)
{...}
else if (вариант 2)
{...}
...
else
{...}
Or like this:
switch(выражениеДляВыбора) {
        case (meaning 1):
                Код1;
                break;
        case (meaning 2):
                Код2;
                break;
...
        case (meaning N):
                КодN;
                break;
        default:
                КодВыбораПоУмолчанию;
                break;
        }
Kotlin uses the when statement for such expressions (although if/else can also be used):
val x = 5
val result = when(x) {
        0, 1 -> "cool"
        2 -> "bad"
        5 -> "normal"
        else -> "error"
}
System.out.println(result)
Here we didn’t just go through the chain of conditions, but also assigned the entire expression to the result variable at once, which shortened us a lot of lines of code. But still, if you have only two options in the branch, I recommend using the usual if..else. The when construct will be shorter from only three options. Moving on - Constructors . Here is a fairy tale. Just compare code in Java and Kotlin. Java:
public class Person {

    private String firstName;
    private String lastName;
    private int age;

    public Person(String firstName, String lastName, int age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
Kotlin:
class Person(private val firstName: String,
             private val lastName: String,
             private var age: Int) {
}
It may seem that something was not added in the Kotlin code. But no, these are two identical codes in different languages. Let's understand a little. In Kotlin, the constructor can be written directly in the body of the class name (but if you want, you can do it the old fashioned way, as in Java). So, we have registered three variables, in Java we have created a constructor, getters and one setter for the age variable. In Kotlin, as we remember, the val variable is read-only, and therefore the setter for these variables is not available (Kotlin implements getters-setters under the hood itself). The var variable makes it possible to use a setter. As a result, in almost one line, we wrote the same thing that took more than a dozen lines in Java. Here I recommend reading more about the data class in Kotlin. But that's not all that constructors in Kotlin are good at. And what, if you need two constructors? What if there are three? In Java it would look like this:
public Person(String firstName, String lastName, int age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

public Person(String firstName) {
        this.firstName = firstName;
    }
Nothing complicated, as many designers as needed, they did so much. In Kotlin, you can get by with a single constructor. How? It's simple - default values.
class Person(private val firstName: String,
             private val lastName: String? = null,
             private var age: Int = 5) {
}
We assigned default values ​​in the constructor and now calling them will look like this:
Person(firstName = "Elon", lastName = "Mask", age = 45)
Person(firstName = "Elon", age = 45)
Person(firstName = "Elon", lastName = "Mask")
Here the question may arise: what is it:
private val lastName: String? = null
What are those question marks? Yes, if the value can be null, then it is set ?. There is also an option like this - !!(if the variable cannot accept null). Read about it yourself, everything is simple there. And we go to the next point. extensions . This is a very cool tool in Kotlin that Java doesn't have. Sometimes we use template methods in a project that are repeated in many classes. For example, like this:
Toast.makeText(this, "hello world :)", Toast.LENGTH_SHORT).show();
In Kotlin, we can extend a class:
fun Context.toast(message: CharSequence) = Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
And then throughout the project, use it like this:
context?.toast("hello world")
We have made an extension for the Context class. And now, wherever context is available, its new toast method will be available. This can be done for any class: String, Fragment, your custom classes, there are no restrictions. And the last point that we will analyze - Working with strings . Everything is simple here. In Java it is written like this:
String s = "friends";
int a = 5;
System.out.println("I have" + a + s + "!");
It's easier in Kotlin:
val s = "friends"
val a = 5
println("I have $a $s!")
These are the nuances that I stumbled over at the beginning of learning Kotlin, I hope this helps you.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION