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

Is there any difference between Kotlin and Java?

Published in the Random EN group
Hi all. I want to tell you a few basic things about the Kotlin language, which will be useful for beginners. It just so happens that now it will be difficult to get into Android development with only one language - most new projects begin to be written in Kotlin, most ready-made projects are written in Java. Is there any difference between Kotlin and Java?  - 1At the moment I have 4 projects at work: two in Kotlin and two in Java (one large main one 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 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 written entirely in Java style, which further added to the misunderstanding: why do I need a new language? But as I used it, I found more and more advantages and now (I’ve 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 decided to start learning Kotlin after Java. Let me also remind you that Android uses Java 8, with the current current version being 14. So, first - 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 whenever possible. It is not necessary to declare the type of a variable if the variable has already been initialized. Second - 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;
        }
In Kotlin, the when operator is used 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 not only went through the chain of conditions, but also immediately assigned the entire expression to the result variable, which saved us quite a few lines of code. But still, if you have only two options in a branch, I recommend using the usual if..else. The when construction will be shorter only from three options. Let's move on - Constructors . It's a fairy tale here. Just compare the 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 left unfinished in the Kotlin code. But no, these are two identical codes in different languages. Let's figure it out 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 written 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 getter-setters under the hood itself). The var variable allows you to use a setter. As a result, we wrote almost in one line the same thing that took more than a dozen lines in Java. Here I recommend reading more about data classes in Kotlin. But that's not all that Kotlin constructors are good at. But 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, just as many designers as needed, that’s what they did. In Kotlin you can get by with just one 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")
The question may arise: what is this:
private val lastName: String? = null
What are these other 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, it’s all simple. And we move on to the next point. Extensions . This is a very cool tool in Kotlin that is not available in Java. Sometimes in a project we use template methods 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 use it like this throughout the project:
context?.toast("hello world")
We made an extension for the Context class. And now wherever the 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 we’ll look at is 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 upon at the beginning of learning Kotlin, I hope this will help you.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION