Tech radar: Perfect Support for Android gives an extra boost to the rapidly growing Kotlin language, and we’re keeping a close eye on the progress of Kotlin/Native, which is based on LLVM and can compile Kotlin code into Native executables. We’ve already seen the benefits of null-pointer safety, data classes, and the ease of building DSLS when developing Android applications using the Anko library. Although the initial compilation is slow and only IntelliJ offers first-class IDE support, we recommend giving this new, clean, modern language a try.

I’ve been asked to share Kotlin on several different occasions due to the recent opportunity to use Kotlin’s popular language on client projects, and one of the most frequently asked questions in the process is — Why are we trying Kotlin?

(Photo from: Suo.im /4hXHdp)

In fact, the client completed their back-end technology selection early last year, and Kotlin has since become the project’s primary language for building back-end microservices. Therefore, I did not give a good answer in these shares, and the question itself also aroused my thinking.

First of all, let’s take a look at the Kotlin language’s features. The official list lists four notable features:

  • Concise Consice
  • Security Safe
  • The development Tool is tool-friendly
  • Interoperability with Java Interoperable

Concise Concise

Kotlin’s brevity is evident in many ways, most immediately to a Java programmer in the omission of the semicolon from Kotlin syntax and the omission of the new keyword when constructing an instance of a class. Here is the standard Kotlin code:

fun sayHi(name: String): String {
    val sb = StringBuilder(str = "Hi ")
    sb.append(name)
    return sb.toString()
}
Copy the code

Let’s look at another sample code from Kotlin’s official website to get a sense of Kotlin’s brevity:

data class Customer(val name: String, val email: String, val company: String)
Copy the code

A single line of code implements a Pojo containing constructor and default implementations of getters, toString, equals, hashCode, and copy. The same Java implementation takes about 50 + lines of code, and even with Lombok’s help it still takes about a dozen lines.

Kotlin also encapsulates the Java collection classes and provides very rich collection operations. This, combined with very compact Lambda expressions, makes the calls more compact.

val numbers = 1.. 10 val doubles = numbers.map {it * 2} val sumOfSquares = doubles.fold(0) {x,y -> x+y}Copy the code

In addition to this, Kotlin provides a number of features like string templates, standard libraries, and operator overloading that make code very concise and readable, greatly improving the developer experience.

In terms of actual projects, Kotlin’s simplicity is evident in the number of lines of code written through Kotlin (including test code), a Spring Boot microservice that provides 24 apis. A microservice of the same size written in Java would have much more code than that.

Security Safe

One of the most common pitfalls in many programming languages, including Java, is to access a null pointer, causing a null pointer exception. Kotlin’s security is mainly reflected in its null-safety support. Making code aware of possible NullPointerExceptions at compile time makes It easy for Java Developer to get rid of NullPointerExceptions.

var output: String
output = null // Compilation error

val name: String? = null // Nullable type
println(name.length()) // Compilation error
Copy the code

Kotlin also offers automatic transformation and type inference features that provide convenience while providing security checks.

Kotlin automatically converts Any to Invoice after checking for true:

fun calculateTotal(obj: Any) {
    if (obj is Invoice)
        obj.calculateTotal()
}
Copy the code

The development Tool is tool-friendly

This characteristic need not say more, quote the official website that ao Jiao’s original words is “It’s what we do best!”

Interoperability with Java Interoperable

In short, the feature is that Kotlin and Java can call each other.

This means that we can build our applications using any existing Java libraries, allowing us to enjoy Kotlin’s enjoyable programming experience without having to give up everything we know.

. import org.springframework.data.jpa.repository.JpaRepository import org.springframework.data.jpa.repository.JpaSpecificationExecutor ... interface AreaRepository : JpaRepository<AreaEntity, Long>, JpaSpecificationExecutor<AreaEntity> { fun existsByAreaId(id: UUID): Boolean fun findOneByAreaId(areaId: UUID): AreaEntity? }Copy the code

In this example, a Spring JPA-based Repository was written in Kotlin on the project, and we can see that thanks to Interoperable features, we can rely on a complete Java ecosystem when trying to use Kotlin. We can still use familiar frameworks, build tools, development tools, and test tools.

How to start?

With all these fascinating language features, you might be tempted to try Kotlin. But the reality may be that the project has been under way for a while, and we’ve already built a lot of functionality for the project in Java. Introducing a new language at this point may bring some risk to the project. So how do we get started?

Write unit tests using Kotlin

If you’re more conservative, you can start writing unit tests in your project using Kotlin alone. Thanks to Interoperable, it’s easy to use Kotlin to write unit tests for Java classes. This way you don’t have to worry about risking your business code by trying Kotlin, and you can also try out the various features of the Kotlin language while writing unit tests.

Use Kotlin to extend

You can also use Kotlin to enrich the Library used in your project and the Kotlin Extensions to extend existing types without requiring inheritance. Or write utility classes directly to serve the project through Kotlin.

//Extensions.kt
fun String.lastChar() = this.get(this.length - 1)
fun KPerson.fullName() = "${this.firstName} ${this.lastName}" //String template
Copy the code
//Java JUnit test
Test
public void lastChar() throws Exception {
 assertEquals('n', Extensions.lastChar("Kotlin"));
}

Test
public void fullName() throws Exception {
  KPerson k = new KPerson("Foo", "Bar", Gender.MALE, 18);
  assertEquals("Foo Bar", Extensions.fullName(k));
}
Copy the code

Use Kotlin to rewrite microservices

If you are using a Spring Boot-based microservice, it is perfectly acceptable to pick a lower-priority service and gradually rewrite it through Kotlin. You will find that the transition will happen very smoothly. Because Kotlin doesn’t change the way you build microservices through Spring Boot.

All three methods allow you to try Kotlin with manageable risks. Let you feel the beautiful programming experience brought by Kotlin language at the same time, let the whole team gradually familiar with Kotlin language. You’ll find that learning Kotlin is really easy for a Java programmer, and once you start, you can’t go back.

Technology of radar

Just when we were on the fence about whether or not to give Kotlin a try, Kotlin’s appearance on the latest tech radar gave us yet another reason to resist Kotlin. While radar’s description has focused more on Kotlin’s impact in the Android Native space, with support from the Spring community and more successful projects, we believe Kotlin will continue to move toward the center of radar.

Finally, I would like to share some related resources that I found good while studying Kotlin:

  • Github.com/Kotlin/kotl…
  • Github.com/dkandalov/k…
  • blog.kotlin-academy.com/
  • Player.oreilly.com/videos/9781…
  • Spring. IO/blog / 2016/0…
  • www.amazon.cn/dp/B074BNVC…

For more insights, please follow our wechat official account: Sitvolk

WeChat
Sina Weibo
Evernote
Pocket
Instapaper
Email
LinkedIn
Pinterest