简评:Pinterest 已经开始用 Kotlin 来进行开发了,并且看样子用得还挺开心。
虽然最近 Kotlin 变得越来越火热,但你仍然可能问自己为什么要用 Kotlin。难道有什么是 Kotlin 能做而 Java 不能做的吗?虽然两者能做的事没有本质的区别,但确实有些事 Kotlin 能干的更出色。这篇文章中我们关注两个地方:类属性和可空判断。
首先,我们从一个 user model 开始,这是最常见的 model 类。在 Java 中你可能会这么写:
public final class User {
@NotNull
private final String email;
private final int age;
public User(@NotNull String email, int age) {
if (email == null) {
throw new RuntimeException("Email can't be null");
}
super();
this.email = email;
this.age = age;
}
@NotNull
public final String getEmail() {
return this.email;
}
public final int getAge() {
return this.age;
}
public String toString() {
return "User(email=" + this.email + ", age=" + this.age + ")";
}
public int hashCode() {
return (this.email != null ? this.email.hashCode() : 0) * 31 + this.age;
}
@NotNull
public final User copy(@NotNull String email, int age) {
Intrinsics.checkParameterIsNotNull(email, "email");
return new User(email, age);
}
public boolean equals(Object otherObject) {
if(this != otherObject) {
if(otherObject instanceof User) {
User otherUser = (User)otherObject;
if(this.email.equals(otherUser.email) && this.age == otherUser.age) {
return true;
}
}
return false;
} else {
return true;
}
}
}
这段大约 50 行的代码用来创建 User model 类所需的 getter, setter 和 equals 函数。
现在,让我们来看看 Kotlin:
data class User(val email: String, val age: Int)
没错!Kotlin 只需要一行代码,而且事实上 Kotlin 的代码还同时保证了在编译时传入的参数值不会为 null。
现在让我们深入一下 Kotlin 的 Nullability 特性。
当我们在定义 kotlin 方法时,必须指定是否允许其可以为 null,默认情况下,对象不能为 null。
比如,我们用 Java 写一个简单的事件记录类:
public class LoggingClass {
private final User myUser;
public LoggingClass(User myUser) {
this.myUser = myUser;
}
public void logEvent(String eventName) {
String userEmail = myUser.getEmail();
AnalyticsClient.logEvent(eventName, userEmail);
}
}
这里的问题是,如果 myUser 为 null,那么调用 logEvent
会导致 NullPointerException。所以在很多类似的 Java 代码中都会加上空值判断:
public class LoggingClass {
private final User myUser;
public LoggingClass(User myUser) {
this.myUser = myUser;
}
public void logEvent(String eventName) {
if (myUser != null) {
String userEmail = myUser.getEmail();
AnalyticsClient.logEvent(eventName, userEmail);
}
}
}
但事实上虽然阻止了崩溃,但问题依旧存在,只是变成了默默的失败 - 方法没有起作用。
现在来看看 Kotlin 的实现:
class LoggingClass(private val myUser: User) {
fun logEvent(eventName: String) {
val userEmail = myUser.email
AnalyticsClient.logEvent(eventName, userEmail)
}
}
Kotlin 的实现直接在编译期就阻止了 null 的传入:
这也就意味着你根本不需要担心 user 对象可能为空,方法也都会按照预想的工作。
那么,Kotlin 是怎么来实现的这一功能?其实反编译一下就完全清楚了:
public LoggingClass(@NotNull User myUser) {
Intrinsics.checkParameterIsNotNull(myUser, “myUser”);
super();
this.myUser = myUser;
}
在 Pinterest 的尝试中,Kotlin 确实让我们的开发人员提高了效率,减少了错误还减轻了压力,不需要花时间再写那些类似的模板代码,而能花更多的时间在产品创新,为用户带来更好的体验。
另外,Pinterest 还有其他两篇关于 Kotlin 的文章,感兴趣的同学可以看看:
原文:Anything Java can do Kotlin can do better
本文作者:Hevin,已获授权,未经作者同意,请勿转载。