Kotlin is a good language for Java developers to expand their horizons. It complements and enhances what you can already do with Java and provides powerful features within the JVM ecosystem. Best of all, switching between Java and Kotlin is so simple that you don’t have to strain your already overworked brain to learn and use Kotlin.
Getting started with Kotlin
Like Java, you must install a JDK to use Kotlin. command line tool SDKManYou can easily install and manage Kotlin using .
$ sdk install kotlin 2.0.20
$ kotlin -version
Kotlin version 2.0.20-release-327 (JRE 23-ea+24-1995)
Simple after installation Main.kt You can create a file and run it.
// Main.kt
fun main() {
println(“Hello, InfoWorld!”)
}
To compile, enter:
$ kotlinc Main.kt
This command is for class file MainKt.classIt outputs and can be executed in the same way as other files as follows.
$ java MainKt
Hello, Kotlin!
As shown above, functions without return values are like Java. void There is no return value declared, simply no return modifier at all. Unlike Java fun You can declare functions outside of a class using keywords. Simple case functions don’t have the pitfalls of Java. i.e. package, class name or public static void There is no qualifier. Kotlin also has all of these features, but hides them by default and uses rules to provide simpler syntax in the dictionary.
In this section, you learned how easy it is to write code and run it inside the JVM in Kotlin, a streamlined, extended version of Java. Although it is not common to run Kotlin with Java tools, the relationship between Kotlin and Java can be clearly seen through examples. In general, Kotlin kotlin You run it using a runtime or a build tool like Gradle, which we’ll look at later.
First-class functions in Kotlin
Kotlin is a first-class functional language, allowing you to pass and return function references from other functions. This provides considerable flexibility.
Also, in many cases, it is okay to use Kotlin and Java code together.
// Main.kt
fun main() {
System.out.println(“Hello from Java, InfoWorld!”);
println(“Hello, InfoWorld!”)
}
However, there are cases where standard Java is invalidated due to some differences in Kotlin syntax. First of all, Kotlin does not have or allow primitive types. In that respect, it is more like Java than Java. In other words, everything in Kotlin is an object. int, long, double, char There are no exceptions. (Project Valhalla is taking Java in a similar direction.)
Additionally, Kotlin clearly distinguishes between mutable and immutable variables. This is also a common trend in modern languages. In every situation where an immutable version can be used, the complexity of the program is reduced. In Kotlin valis immutability, ourmeans variable variable.
val myValInt: Int = 10;
var myVarInt: Int = 10
// myValInt++;
By now you’ve probably noticed that semicolons are optional in Kotlin, just like in JavaScript. A common practice in Kotlin is not to use a terminating semicolon.
Kotlin infers types as follows:
val myString = “FooBar”;
println(“My string ${myString} is a classic.”);
In the code above, Kotlin’s built-in String You can also see interpolation support, which uses a similar syntax to many template tools. Dollar sign braces (${})Is ${myString.upperCase()}It can include expressions such as . If your variable name does not contain special characters, you can use the following simplified format:
println(“When in doubt, $myString.”);
Below is all of Java’s type system, which you can access by typing:
println(myString::class.java.typeName); // Outputs “String”
null handling
Kotlin’s representative feature is a clearer null It’s processing. NullPointerExceptionis one of the familiar exceptions in Java. In Kotlin, variables basically have nullThis is not allowed. The compiler uses null Setting is not allowed. nullIf you need this possible variable, you can set it as follows.
val myNullableString: String? = null
In Kotlin nullto deal with .?and 😕 There are also operators. .? is similar to the optional chaining operator recently added to JavaScript, without the need for verbose checking. null It allows simple processing of values.
possiblyNull.?possiblyNullMember.?anotherMember
any part nullIf the entire expression is without error nullreturns . null Combining operator (?:also known as the Elvis operator because it is reminiscent of Elvis’s hair style), the left nullcognitive testing nullIf not, it can be returned. Otherwise similarly nullReturns the right side of .
something 😕 somethingElse
somethingthis nullThis side somethingElseYou will receive
Collection processing
Of course, it must be able to handle collections of variables. Kotlin has all the common sets, lists, and maps, all of which allow mutable and immutable transformations. If you want a list of variable strings, enter the following:
import kotlin.collections.*;
fun main() {
val books: MutableList = mutableListOf(“Autobiography of a Yogi”, “Slaughterhouse Five”, “Phaedrus”);
println(books(2));
}
In this code, the collection library is imported. This library is in the Kotlin standard library, so you can compile it as follows.
$ kotlinc Main.kt
However, it does not execute and the following results occur.
$ java MainKt
Exception in thread “main” java.lang.NoClassDefFoundError: kotlin/collections/CollectionsKt
at MainKt.main(Main.kt:14)
at MainKt.main(Main.kt)
Caused by: java.lang.ClassNotFoundException: kotlin.collections.CollectionsKt
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:528)
As a familiar Java error, CollectionsKtIt says that the class definition for could not be found. To fix this error, you need to include the standard library during runtime as follows:
$java -cp
/home/matthewcarltyson/kotlin:/home/matthewcarltyson/.sdkman/candidates/kotlin/current/lib/kotlin-stdlib.jar MainKt
Phaedrus
This command in Java kotlin-stdlib.jarInstructs to include (the location may vary depending on the usage environment). Another approach is stdlibautomatically includes kotlin It uses runtime.
$ kotlin MainKt
Kotlin also provides strong functional programming support. For example, about the book you want books To check the collection, enter the following:
println(“Phaedrus” in books) // outputs true
You can also access lists like arrays using square brackets.
println(books(2)) // outputs “Phaedrus”
Using Kotlin and Gradle together
Gradle is often used as a build tool in Kotlin. Instead of Groovy Kotlin DSLThis is because you can use .
The easiest way to use Gradle and Kotlin together is to Gradle initto start a new project. This command runs an interactive survey from the command line. You can see it below along with my response.
$ gradle init
Select type of project to generate: 2: application
Select implementation language: 4: Kotlin
Split functionality across multiple subprojects?: 1: no – only one application project
Select build script DSL: 2: Kotlin
Generate build using new APIs and behavior (some features may change in the next minor release)? (default: no) (yes, no): no
Project name (default: kotlin): kotlin
Source package (default: kotlin): com.infoworld
The result of my choice is a Kotlin application that uses Kotlin as the build script language. Now you can run this simple program from your project root like this:
$ ./gradlew run
When you run the program, the “Hello, World” greeting is displayed. The project structure is as follows.
/settings.gradle.kts – Global settings for Gradle
/app/ build.gradle.kts – The build file
/app/src/main/kotlin/com/infoworld/App.kt – The single source file
App.kt In the file you can see the following:
class App {
val greeting: String
get() {
return “Hello World!”
}
}
fun main() {
println(App().greeting)
}
It has a few features I haven’t seen yet, including the use of package declarations. (In Kotlin, the package and directory structures do not have to match.)
You can also see a simplified Kotlin syntax for class declarations. Classes in Kotlin Default visibility is publicsince Appis a public class. In it greetingread-only String There is a member (valdeclares a read-only variable). greeting The properties are get() Declare a function. Executes when accessed using the dot operator and has a simplified getterIt can be seen that
Now for a bigger task, Star Wars APILet’s download the character data for Chewbacca from here. App.kt You can edit the file as follows:
package com.infoworld
import com.google.gson.Gson
import java.net.URL
class App {
fun fetchAndPrintCharacterInfo(url: String) {
val gson = Gson()
val response = URL(url).readText()
val character = gson.fromJson(response, StarWarsCharacter::class.java)
println(“Name: ${character.name}”)
println(“Height: ${character.height}”)
}
}
data class StarWarsCharacter(
val name: String,
val height: String,
)
fun main() {
val chewbaccaUrl = “https://swapi.dev/api/people/13/”
val app = App()
app.fetchAndPrintCharacterInfo(chewbaccaUrl)
}
Kotlin’s designed to store information here. data class(similar to Java’s value object).
StarWarsCharacter In class getter, setter, hashCode, toString, equals There are all common methods, etc. This is ideal for unpacking API data into a container, as we do here.
/app/build.gradle.ktsof dependencies Add the following dependencies to the section:
implementation(“com.google.code.gson:gson:2.9.1”)
This will allow you to process the JSON returned from the API. Now, if you run the app, you can see information about Chewbacca.
> Task :app:run
Name: Chewbacca
Height: 228
Hair color: null
Eye color: null
BUILD SUCCESSFUL in 2s
conclusion
The appeal of Kotlin for Java developers is that it fits easily into existing thinking models. Kotlin allows you to program within the JVM, which has powerful optimizations and a vast ecosystem, but is in some ways “more Java than Java,” while still using an easy-to-understand and powerful functional language. Kotlin can also be used with Java, so you don’t have to choose between the two.
Kotlin has many more features than those covered here, including extension functions (which allow you to add class functions without subclassing them), coroutines, more functional features, the absence of checked exceptions, and a streamlined approach to object-oriented programming. . We will continue to look at Kotlin and its features in the next article.
editor@itworld.co.kr
Source: www.itworld.co.kr