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; } }
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)
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"
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
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")
##
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
Your util package!
4. You can forget ViewBinding
你还记得findViewById()method()吗? 我们相信你不喜欢它。 我们也不是。 此外,我们不想为我们需要访问的每个视图声明变量和Butterknife注释。 你可以忘记与Kotlin Android Extensions的视图绑定。 不再需要创建变量和绑定视图。 您可以使用在xml布局中声明的标识符直接访问您的视图。 这太简单了,不是吗? 基本上,findViewById()方法仍在使用中。 但是没有必要自己写。 Kotlin会为你做。 当您使用Android扩展时,findCachedViewById()函数和HashMap实例将会自动生成。 每次通过其标识符访问您的视图将被一个新的函数调用替换。 如果是第一次访问视图,此函数将调用通常的findViewById()函数,并将接收的视图添加到HashMap中,以便在下次访问视图时从中检索视图。 5. 你可以更容易地使用集合 让我们谈谈Kotlin的集合。 因为我们经常需要使用数据模型集合执行困难的操作。 例如,我们可能有一个学生名单,我们需要从中检索三个A级成绩的学生和两个B成绩的学生。 看看Kotlin的解决方案: 下面是我们如何解决Java中的同样的问题: 这只是一个小例子,说明如何在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!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" }
}
}
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)
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);
}
}