This is an article to tell you that I was very happy with the transition from Java to Kotlin.
I used to program in Java a while back. But Java has its drawbacks. This is, for example:
: warning: This is an article about migrating from Java. JavaScript is a completely different language. Please be careful.
NullPointerException
Null may be returned as a return value from the API, or null may be passed as an argument. The former can be avoided by using the Optional
When declaring a variable, describe the type such as List <String> words
. However, it would be nice if we could infer it. Now you can use var
, but not for instance fields etc.
In Java, you need to write getters / setters for each encapsulation, which are a bit verbose. Class constructors and overloads are pretty tedious.
In Java, when creating a method (higher-order function) that receives a function, such as Function <T, R> You need to write a slightly longer type. It has a fixed naming convention, but it's still hard to read.
If the grammar was completely different when you migrated the language, it would be unfamiliar. It may be dynamic, or it may be functional programming.
If the new destination programming language is completely incompatible, it will take a lot of time. If possible, I would like you to use the existing Java programs.
Kotlin separates types that can be null and types that can't. String?
May contain null. String
cannot contain null.
In Java, the following classes
public class Pen {
private int ink;
public Pen(int ink) {
setInk(ink);
}
public int getInk() {return ink;}
public void setInk(int ink) {
if (ink < 0)
throw new IllegalArgumentException("The argument is 0 or less. Specified value:" + ink);
this.ink = ink;
}
}
In Kotlin
class Pen(ink: Int = 0) {
var ink:Int = ink
set(value) {
if (ink < 0)
throw IllegalArgumentException("The argument is 0 or less. Specified value:${value}")
field = value
}
}
Simply call. If the setter is unchecked,
class Pen(var ink:Int)
Only. If you follow the naming conventions getXXX and setXXX, you can access it like a field like pen.ink
. By the way, getters / setters are generated at compile time for the fields defined earlier in Kotlin.
The variable type can omit the : Int
part if it is initialized together. For functional programming, it's as easy as Haskell with String-> Int
.
In fact, Kotlin is converted to a class file when compiled. In other words, it runs on the JVM like Java. Kotlin and Java can coexist, and Kotlin can use Java libraries, inherit from them, and vice versa.
I use an IDE called IntelliJ. It has a function to convert Java to Kotlin (existing files and copy / paste), which is very helpful. Languages that run on the JVM include Scala, Groovy, and Ruby (jRuby), but I'm not very familiar with the syntax in Ruby, Scala is slow to compile, and Groovy chose Kotlin because it's dynamically attached. Now, let's go ** to ** migrate ** to Kotlin ** (puns).
Recommended Posts