Home Java javaTutorial Detailed comparison of the basic syntax of Java and Kotlin

Detailed comparison of the basic syntax of Java and Kotlin

May 21, 2017 am 10:32 AM

This article mainly introduces the relevant information on the comparison of the basic syntax of Kotlin and Java. Friends in need can refer to it

Comparison of the basic syntax of Kotlin and Java

Kotlin Younger than Java, but it is a very promising programming language with a growing community. Everyone was talking about it and saying it was cool. But why is it so special?

We have prepared a series of articles to share our experience in developing Android applications in Kotlin. We'll discuss the differences between Kotlin and Java in terms of syntax, usability, UI performance, and asynchronicity so you can decide which language is best for you.

Let's start with some basic syntax differences. Here’s the first one:

1. With Kotlin, you can do more with less code

One of the main advantages of Kotlin It's the simplicity of it. You get more functionality with less code. And the less code you write, the fewer mistakes you make. this is very simple. Let

Let’s look at the basics of Kotlin, starting with classes.

public final class Person {
  private String name;
  private int age;
  private float height;

  public Person(String name, int age, float height) {
    this.name = name;
    this.age = age;
    this.height = height;
  }

  public Person(String name, int age) {
    this.name = name;
    this.age = age;
    this.height = 1.8f;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }

  public float getHeight() {
    return height;
  }

  public void setHeight(float height) {
    this.height = height;
  }

  @Override
  public String toString() {
    return "Person{" +
        "name='" + name + '\'' +
        ", age=" + age +
        ", height=" + height +
        '}';
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    Person person = (Person) o;

    if (age != person.age) return false;
    if (Float.compare(person.height, height) != 0) return false;
    return name != null ? name.equals(person.name) : person.name == null
  }

  @Override
  public int hashCode() {
    int result = name != null ? name.hashCode() : 0;
    result = 31 * result + age;
    result = 31 * result + (height != +0.0f ? Float.floatToIntBits(height) : 0);
    return result;
  }  
}
Copy after login

The above is a usual Java class. It doesn't do much. It just contains some data. But it's painful to see how big this code is when you realize the shortcomings it brings to the table. To encourage you, we will give you an equivalent class written in Kotlin.

data class Person(var name: String,
         var age: Int,
         var height: Float = 1.8f)
Copy after login

Yes, you will automatically get the required getters, setters, equals(), hashcode(), toString() and copy() functions for your data class ! Of course, you can easily override these functions, but in most cases just declaring the class and its properties is enough.

This is exactly what we mean when we say Kotlin is concise.

2. You can avoid NullPointerException

Now we want to remind you of the biggest pain in many programming languages ​​- Null Pointer abnormal. We can hardly imagine how many developers have suffered from the null pointer since Tony Hall invented it in 1965 while trying to make things simpler.

Sadly, we can't come back in time to prevent Tony from making this mistake. But using Kotlin we can now easily escape NullPointerException.

val person: Person? = null
...
person?.name = "John"
Copy after login

If a variable is nullable, the compiler will not allow you to access it without proper checking. Kotlin forces you to use it? Operator. This prevents the application from automatically crashing.
How does it work under the hood? Let's review the generated bytecode.

L2
LINENUMBER 18 L2
ALOAD 3
DUP
IFNULL L3
LDC "John"
INVOKEVIRTUAL igalata/com/kotlinexample/Person.setName (Ljava/lang/String;)V
GOTO L4
L3
POP
Copy after login

As you can see, we have the same null check here. The developers at JetBrains (who created Kotlin) knew that checking our variables every time was the only way to avoid NullPointerException. But they also know that Android developers don't want to deal with NullPointerException in their projects. They might be thinking: "Why not automatically generate this check if the variable is nullable?

The developers at JetBrains just did this and made our lives easier!

3. You can get rid of util classes

Let’s talk about the ugly things about using util classes. Have you ever had a project without them? We barely remember it all. A clever solution - extension functions - helps you get rid of all util classes once and for all.

An extension function is almost a normal Kotlin function but when you declare it you need to specify what the instance will have. Class that extends functionality.
fun Context.toast(text: String) = Toast.makeText(this, text, Toast.LENGTH_SHORT).show()

Note that 'this', we use Parameter passed to makeText() method? It is not an instance of the class we declare this function, but a Context instance. Now you can call this function directly from your Activity or any other Context instance:


##

toast("Hi")
Copy after login

You should remember that extension function does not modify the class it extends in any way. So how does it work without changing the original class? Let's see the bytecode again? .


##

public final toast(Landroid/content/Context;Ljava/lang/String;)V
  @Lorg/jetbrains/annotations/NotNull;() // invisible, parameter 0
  @Lorg/jetbrains/annotations/NotNull;() // invisible, parameter 1
  L0
  ALOAD 1
  LDC "$receiver"
  INVOKESTATIC kotlin/jvm/internal/Intrinsics.checkParameterIsNotNull (Ljava/lang/Object;Ljava/lang/String;)V
  ALOAD 2
  LDC "text"
  INVOKESTATIC kotlin/jvm/internal/Intrinsics.checkParameterIsNotNull (Ljava/lang/Object;Ljava/lang/String;)V
  L1
  LINENUMBER 31 L1
  ALOAD 1
  ALOAD 2
  CHECKCAST java/lang/CharSequence
  ICONST_0
  INVOKESTATIC android/widget/Toast.makeText (Landroid/content/Context;Ljava/lang/CharSequence;I)Landroid/widget/Toast;
  INVOKEVIRTUAL android/widget/Toast.show ()V
  L2
  LINENUMBER 32 L2
  RETURN
  L3
  LOCALVARIABLE this Ligalata/com/kotlinexample/MainActivity; L0 L3 0
  LOCALVARIABLE $receiver Landroid/content/Context; L0 L3 1
  LOCALVARIABLE text Ljava/lang/String; L0 L3 2
  MAXSTACK = 3
  MAXLOCALS = 3
Copy after login

Ha! Your function implicitly receives an instance of the class it extends as the first argument. Any access to "this" in the body will be replaced with an access to the first parameter. No magic really. You can use this function anywhere in your project

.

Your util package!

4. You can forget ViewBinding

你还记得findViewById()method()吗? 我们相信你不喜欢它。 我们也不是。 此外,我们不想为我们需要访问的每个视图声明变量和Butterknife注释

你可以忘记与Kotlin Android Extensions的视图绑定。 不再需要创建变量和绑定视图。 您可以使用在xml布局中声明的标识符直接访问您的视图。


public class MainActivity extends AppCompatActivity {
  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button button = (Button) findViewById(R.id.button);
    final TextView text = (TextView) findViewById(R.id.text); 
    button.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        text.setText("You've clicked a button");
      }
    });
  }
}

class MainActivity : AppCompatActivity() {

  override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
    super.onCreate(savedInstanceState, persistentState)
    setContentView(R.layout.activity_main)

    button.setOnClickListener { text.text = "You've clicked a button" }
  }
}
Copy after login

这太简单了,不是吗?

基本上,findViewById()方法仍在使用中。 但是没有必要自己写。 Kotlin会为你做。

当您使用Android扩展时,findCachedViewById()函数和HashMap实例将会自动生成。 每次通过其标识符访问您的视图将被一个新的函数调用替换。 如果是第一次访问视图,此函数将调用通常的findViewById()函数,并将接收的视图添加到HashMap中,以便在下次访问视图时从中检索视图。

5. 你可以更容易地使用集合

让我们谈谈Kotlin的集合。 因为我们经常需要使用数据模型集合执行困难的操作。 例如,我们可能有一个学生名单,我们需要从中检索三个A级成绩的学生和两个B成绩的学生。

看看Kotlin的解决方案:


var students = listOf(Student("John", 0), Student("Julia", 2), Student("Matt", 1),
        Student("Katie", 0), Student("Dan", 0))

var firstList = students.filter { it.mark == 0 }.take(3)
var secondList = students.filter { it.mark == 1 }.take(2)
Copy after login

下面是我们如何解决Java中的同样的问题:


ArrayList<Student> students = new ArrayList<Student>() {{
      add(new Student("John", 0));
      add(new Student("Julia", 2));
      add(new Student("Matt", 1));
      add(new Student("Katie", 0));
      add(new Student("Dan", 0));
}};

ArrayList<Student> firstList = new ArrayList<>();
ArrayList<Student> secondList = new ArrayList<>();

for (Student student: students) {
      boolean isFirstFilled = firstList.size() >= 3;
      boolean isSecondFilled = secondList.size() >= 2;

      if (isFirstFilled && isSecondFilled) break;
      int mark = student.getMark();
      if (mark == 0 && !isFirstFilled) {
        firstList.add(student);
      } else if (mark == 1 && !isSecondFilled) {
        secondList.add(student);
      }
    }
Copy after login

这只是一个小例子,说明如何在Kotlin和Java中使用集合,但你可以看到差别! 你能想象如果我们处理一个大项目的集合,Kotlin会有什么区别吗?

The above is the detailed content of Detailed comparison of the basic syntax of Java and Kotlin. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

See all articles