iwillteachyoukotlin
Shares

Download The Ultimate Tutorial: Getting Started With Kotlin

350 pages of hands-on tutorial right into your email inbox. Learn how to use state of the art development environment and build a full-fledged command-line application. You will receive free updates to the tutorial. Start learning Kotlin today!

Archive Monthly Archives: January 2019

How to Try Kotlin in Java Backend Codebase Without Risk

Shares

Okay, a show of hands.

Who’s heard of this lovely and astounding programming language Kotlin, and wanted to try it out on the real backend project…

and couldn’t?

Yeah, most of us. This is common. The team discusses that everyone really wants to go Kotlin, and they still decide to create that new codebase in Java.

You and your fellow colleagues are afraid that this will go crazy wrong, right?

And you are right to have such a feeling, as you don’t have enough confidence yet to make the switch. What if the whole team is still learning this new technology, and there is an unexpected challenge that nobody can resolve for weeks?

Yeah… tricky situation.

Now, you’re probably quite a bit into this project, and your backend codebase is all in verbose Java, and you think: “No way I can try Kotlin now! Not until next one…”

Wrong.

There is no point in waiting until the next opportunity because of the high chances that it’ll turn out the same!

Now, what if I told you that you can still try out Kotlin together with your teammates in this codebase without any risks, and no strings attached?

Let me explain.

Mixing Java and Kotlin code

With Kotlin’s 100% bidirectional interoperability, it’s possible to mix Java and Kotlin code easily.

What this means, is that you can convert a single file from Java to Kotlin to get the feels of what it’ll look like. And everything will work just like before.

Now, what if I told you that such a conversion is one hotkey away?

Let me show an example. Imagine you had this simple service class in your Java backend application:

// QuizService.java
package com.iwillteachyoukotlin.quizzy;

import org.springframework.stereotype.Service;

@Service
public class QuizService {

    private final QuizRepository quizRepository;

    public QuizService(QuizRepository quizRepository) {
        this.quizRepository = quizRepository;
    }

    public Quiz create(Quiz quiz) {
        if (quiz.id != null) {
            throw new BadRequestException("id should be empty");
        }

        return quizRepository.save(quiz);
    }

    public Quiz getQuiz(int quizId) {
        return quizRepository
                .findById(quizId)
                .orElseThrow(() -> new NotFoundException("quiz not found"));
    }
}

Now, you can press CMD+ALT+SHIFT+K (or CTRL+ALT+SHIFT+K), or you could use Convert Java File to Kotlin File action:

Open Find Action tool, type convert to kotlin, press enter, and see the file fully convert to kotlin automatically

The result is the following code. Notice how both constructor and field definition has merged into a single declaration in Kotlin:

// QuizService.kt
package com.iwillteachyoukotlin.quizzy

import org.springframework.stereotype.Service

@Service
class QuizService(private val quizRepository: QuizRepository) {

    fun create(quiz: Quiz): Quiz {
        if (quiz.id != null) {
            throw BadRequestException("id should be empty")
        }

        return quizRepository.save(quiz)
    }

    fun getQuiz(quizId: Int): Quiz {
        return quizRepository
                .findById(quizId)
                .orElseThrow { NotFoundException("quiz not found") }
    }
}

Note for Lombok users:

Use Delombok on this file before converting to Kotlin.

Of course, you need to add Kotlin support to your build tool before you can even run this code:

Add Kotlin support to Gradle

(Note: refer to this guide if you’re using Maven)

Add a Gradle plugin appropriately:

plugins {
    id "org.jetbrains.kotlin.jvm" version "1.3.11"
}

Note for Spring Boot users:

You need to add this plugin, so that Kotlin classes will open automatically where needed, so that Spring Boot can use reflection on them:

id "org.jetbrains.kotlin.plugin.spring" version "1.3.11"

And if you’re using JPA/Hibernate entities, you’ll need this plugin:

id "org.jetbrains.kotlin.plugin.jpa" version "1.3.11"

This adds the default constructor for your entities.

Also, you’ll need to add a dependency on Kotlin standard library and reflection library:

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
    implementation "org.jetbrains.kotlin:kotlin-reflect"
    // …
}

Now you have one Kotlin file among the sea of Java files. Java classes are calling this Kotlin code, and this Kotlin code is calling to Java code.

And it all perfectly works. And all tests pass!

Now, simple automatic conversion is ok and all, but it’s not enough to really leverage the power of Kotlin.

1. Use Elvis operator instead of most null checks

If you had any null check anywhere that returns or throws an exception, for example:

fun update(quiz: Quiz): Quiz {
    if (quiz.id == null) {
        throw BadRequestException("id should not be empty")
    }

    return quizRepository.save(quiz)
}

These null checks that either throw or return are usually called guard if statements. In Kotlin these can be done more succinctly with “Elvis” operator ?::

fun update(quiz: Quiz): Quiz {
    quiz.id ?: throw BadRequestException("id should not be empty")

    return quizRepository.save(quiz)
}

2. Convert Optionals to nullable

Another example that can be simplified with Kotlin is the usage of Optional type:

fun getQuiz(quizId: Int): Quiz {
    return quizRepository
            .findById(quizId)
            .orElseThrow { NotFoundException("quiz not found") }
}

Here we’re going to use another method of our repository that returns either a found object or null:

fun getQuiz(quizId: Int): Quiz {
    return quizRepository.findByIdOrNull(quizId)
            ?: throw NotFoundException("quiz not found")
}

As you can see, here we use the Elvis operator, as well. Quite handy, isn’t it?

3. Make JUnit test names more readable

Let’s imagine that the application above had this test in its integration test suite:

@Test
public void failsToCreate_whenIdIsProvided() throws Exception {
    // ARRANGE
    final Quiz quiz = new Quiz(
            42,
            "title",
            "description",
            "cta",
            "https://example.org/image.png"
    );

    // ACT
    final ResultActions actions = mockMvc.perform(post("/quizzes")
            .contentType(APPLICATION_JSON_UTF8)
            .content(objectMapper.writeValueAsString(quiz)));

    // ASSERT
    actions.andExpect(status().isBadRequest())
            .andExpect(jsonPath("$.message", equalTo("id should be empty")));
}

Now, after automatic conversion to Kotlin it’ll look something like this:

@Test
@Throws(Exception::class)
fun failsToCreate_whenIdIsProvided() {
    // ARRANGE
    val quiz = Quiz(
            42,
            "title",
            "description",
            "cta",
            "https://example.org/image.png"
    )

    // ACT
    val actions = mockMvc!!.perform(post("/quizzes")
            .contentType(APPLICATION_JSON_UTF8)
            .content(objectMapper!!.writeValueAsString(quiz)))

    // ASSERT
    actions.andExpect(status().isBadRequest)
            .andExpect(jsonPath("$.message", equalTo("id should be empty")))
}

First, we can throw away this @Throws annotation immediately. It’s mostly useless in Kotlin.

And now, we can use actual human-readable sentences in the method names using backticks:

@Test
fun `create quiz - fails to create when id is provided`() {
    // …
}

My general structure is: “{method name or use case name} – {expected outcome} when {condition}.”

4. Use lateinit instead of nullable

In cases, when something is being provided later (like dependency injection, or initialized in the set-up section of the test suite), you should use lateinit instead. It’s much cleaner.

Look, this code is a result of automatic conversion:

@SpringBootTest
@RunWith(SpringRunner::class)
class QuizzesIntegrationTest {

    @Autowired
    private val context: WebApplicationContext? = null

    @Autowired
    private val objectMapper: ObjectMapper? = null

    private var mockMvc: MockMvc? = null

    private var quizId: Int = 0

    @Before
    fun setUp() {
        mockMvc = MockMvcBuilders
                .webAppContextSetup(context!!)
                .build()
    }

    // …

}

All these fields are initialized later, AND before the first usage, so we can tell the compiler about that:

@Autowired
private lateinit var context: WebApplicationContext

@Autowired
private lateinit var objectMapper: ObjectMapper

private lateinit var mockMvc: MockMvc

private var quizId: Int = 0

Now, the problem is that all these nullable values were unsafely unwrapped everywhere in the test suite with !! operator:

a lot of warnings about unnecessary non-null (!!) assertion

Of course, we can fix them all manually, but these are things that tools should fix for us.

And they do, look:

use intent actions menu and select remove unnecessary non-null assertion, it removes !! automatically

It still would be annoying to go through each occurrence though. So we should just apply code cleanups to the whole file:

use find action tool and type code cleanup, the tool window shows up, select a single file only there, and proceed, all unnecessary non-null assertions disappear from the whole file

5. Use named arguments for readability

Now, you see this snippet of code:

// ARRANGE
val quiz = Quiz(
        42,
        "title",
        "description",
        "cta",
        "https://example.org/image.png"
)

We can make this code much more descriptive if we were to use named arguments, like so:

use intent actions menu and choose to add names to call arguments, every argument now is named

Now, you’ll get this cute little readable snippet of code. Also, you can re-order the arguments when you pass them as you wish, and as it makes more sense.

// ARRANGE
val quiz = Quiz(
        id = 42,
        title = "title",
        description = "description",
        ctaText = "cta",
        imageUrl = "https://example.org/image.png"
)

Unfortunately, to make this feature work, the class Quiz can’t be a Java class, it has to be in Kotlin, so we’ll have to convert the entity below to Kotlin:

@Entity(name = "quizzes")
@Data
@RequiredArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties({"hibernateLazyInitializer"})
public class Quiz {
    @Id
    @GeneratedValue
    public Integer id = null;

    public final String title;
    public final String description;
    public final String ctaText;
    public final String imageUrl;

    Quiz() {
        title = "";
        description = "";
        ctaText = "";
        imageUrl = "";
    }
}

This is a result of full (auto + manual) conversion:

@Entity(name = "quizzes")
@JsonIgnoreProperties("hibernateLazyInitializer")
data class Quiz(
        @Id
        @GeneratedValue
        var id: Int? = null,

        val title: String,
        val description: String,
        val ctaText: String,
        val imageUrl: String
)

As you can see we’re getting rid of all the Lombok stuff and using a data class now because it can do most of the things, you would need from the entity.

6+. There is so much more you can improve!

If you want to learn more about how good Kotlin code will look like, I highly recommend to go through the Kotlin Koans.

You can do that right in your browser, or in your IDE if you wish.

Now, remember, at the beginning of this post, I’ve promised the “Without Risk” part, didn’t I?

Trying out without any risks whatsoever

Now, if I decided not to make the switch to Kotlin yet (because I still need to convince my colleagues, for example), I can use Local History feature of my IDE to go back in time to when I started playing with Kotlin:

local history tool window

To open that tool in IntelliJ, you can use the contextual menu on the whole project in the project structure tool. There is an option Local History > Show History there:

right click on the project name in project structure tool, choose Local History - Show History

When you’ve found the place where you started playing with Kotlin, you can revert to the first Kotlin-related change, for example:

choosing revert option on a specific change in the past

Now, there is not a single Kotlin file, and all the tests are passing. This is a handy feature in general if you screwed something up, and haven’t made a commit in Git in a while.

Did that spike your curiosity about Kotlin?

I have written a 4-part (350-pages total) “Ultimate Tutorial: Getting Started With Kotlin” (+ more to come), and you can get it as a free bonus by becoming a member of my monthly newsletter.

On top of just Kotlin, it is full of goodies like TDD, Clean Code, Software Architecture, Business Impacts, 5 WHYs, Acceptance Criteria, Personas, and more.

—Sign up here and start learning how to build full-fledged Kotlin applications!

Thank you and ask for you!

Thank you so much for reading this article! I hope you enjoyed it. Please, tell me what you think about this in the comments!

Also, it would make me so much happier share this post with your friends and colleagues who you think might benefit from it. Or you could share it on your favorite social media!

You are welcome to read my blog about Kotlin, and my blog about TDD and best software engineering practices.

And let’s connect on LinkedIn: I post short weekly updates about software developer’s productivity and happiness, teamwork, mental health, and a bit about Kotlin.

If you want to hear more of my opinions, follow me on Twitter.

Kotlin: How Can a Programming Language be so Young And so Mature at The Same Time?

In this article, we’re going to explore why young programming languages with modern features can’t be adopted quickly. Additionally, we’re going to take a look at one exceptional example that got specific parameters right to be both young, modern and mature, just ready for adoption at small and big scale.

DISCLAIMER: Some details are omitted intentionally. Keep your mind open when reading. If something seems naive, or not entirely true, bear in mind that the author thought into both the front and back sides of the coin, and the unseen third side of the coin, as well. You’re welcome in comments for a more in-depth discussion—it’s going to be worth your time for sure!

We all know that most of us, software developers, love to chase after shiny things just as much as we like to build them. This is not different for programming languages.

And, in this day and age, new young programming languages pop up like these mushrooms:

Why new modern languages can’t be adopted quickly?

A distinct feature of a young language is that creators and community gets the chance to experiment with different features and designs to potentially fix some problems of the existing mature languages. Mind you, any solution to any problem will bring minimum two more subtle issues. So this cycle of continuous improvement will never end.

While young languages can explore more advanced features and designs, they usually don’t have a robust ecosystem of libraries, frameworks, and tooling. Moreover, when the community develops these, people will still have to learn them, and that means that they (albeit temporarily) will be much less productive. And I’m not even going to talk about potential vulnerabilities, bugs, and so on.

Now, wouldn’t it be great if the new young modern language could rely on the existing mature ecosystem? Wouldn’t it be fantastic if using existing libraries, frameworks and tooling was entirely natural and not awkward at all?

If you ask me these questions, I’ll tell you that you’re perhaps describing Kotlin. Kotlin is a programming language where you can naturally use any library, framework or tool from the JVM ecosystem without any awkwardness.

Now, there were languages before, that could do that as well, like Scala, Groovy, Clojure, and so on. And they all got something wrong: natural use.

Why these languages don’t want to rely on the existing mature ecosystem?

Either it wasn’t natural to use the same framework or library, or it was even impossible to use the same tooling. And in the scenario where it would be possible to use same tooling, framework, and libraries naturally; somehow, the majority of the community went out there and built new tools, frameworks, and libraries (I’m looking at you, Scala, and sbt).

My hunch is that this happens because most of the early adopters of these new languages (“promised replacements for Java”) have somewhat an adversarial relationship with Java language and JVM ecosystem.

They hate it.

As early adopters, they set the playing field, because they are in the vast majority in the community during the first few years of the new young language. This way, they get to write all the brand new shiny tools, frameworks and libraries. And they are the ones who start new projects in these languages at actual companies and startups.

This way, the community style sets in: unique tooling, frameworks, and sets of libraries that people use. Sometimes, these are even designed on purpose to be radically different from their older alternatives from the JVM community.

This makes the learning curve very steep, and so the language gets adopted only by like-minded people, and poor developers who just have no choice but to maintain the codebases where this set of tools is being used already.

How to attract different early adopters that will be happy to leverage existing ecosystem?

Kotlin is radically different from this approach. The playing field rule number one: “100% bidirectional interoperability with Java and JVM ecosystem.”

Thus the community attracts fellows who are not looking to do everything in the entirely different approach; instead, they want a more modern language, AND they want to transfer their skills, knowledge, and experience from working with the mature ecosystem like JVM.

These early adopters don’t want to rewrite their existing codebases entirely because they are large, so being able to write only new code in Kotlin, and keep older code in Java helps a lot!

Small story of a fellow software engineer

I’m going to give you a tangible example:

Clara is a software engineer, working for a big organization, mostly working with Java, JVM, and Spring Boot. Clara’s professional level is senior and perhaps even beyond that:

  • she applies best software practices,
  • knows how to design simple software iteratively,
  • can solve any complex problem you throw at her,
  • knows her audience when writing the code (current and expected in the future level of her team members),
  • excellent communicator and team player,
  • teaches and mentors other developers,
  • can take on the role of a team lead today,
  • and lives the life of a life-long learner.

Her current development workflow includes building the application and automating development tasks with Gradle, and she gets her coding done within a modern IDE like IntelliJ. She doesn’t have any of the adversarial feelings towards any of these tools and technologies.

Quite the opposite: she loves them!

Sometimes though, she feels feature envy to all these cool modern programming languages where you could have one-liner data classes, less boilerplate in general, and the null-pointer exception is not a dreaded threat at every step.

And here is Kotlin programming language that recently became “production-ready.”

So she tries out to build a tiny web app (a tad more complicated than “Hello world”). And it seems like she can still use the same build tool—Gradle; and she still can use any of her favorite libraries, and much more critical, she can use the same web framework—Spring Boot.

And using all these things is not awkward at all, and feels just as natural, as in their “home” environment—Java.

Now, she has the next question: “This language is great but quite new… do I have to lose all the great features of my IDE now?” Because that is what happens to most modern languages—the IDE support is lagging way… way behind.

And now she gets pleasantly surprised: 95% of the IDE features that she needs are there and are supported:

  • basic and advanced refactorings,
  • jump to definition,
  • find usages,
  • running application and tests from IDE,
  • running a single test in the current context,
  • debugger,
  • code completion, even cross-language,
  • etc.

And this makes so much sense because the language is developed by the same company that develops the IDE (JetBrains). This certainly ensures that the tooling will be at least somewhat up to speed with the new modern language.

“This all sounds great!” Clara thinks, “Do I have to rewrite my application at work now fully to Kotlin?”

Most important playing field rules fostering the adoption

And she gets pleasantly surprised here as well. All she really needs to do is to add Kotlin Gradle plugin (few lines of change in a single file), and she can start adding Kotlin files to the source code base. All the old files, written in Java, are still working correctly.

Moreover, cross-language calls are working out of the box: she can call Java code from Kotlin, and Kotlin code from Java; AND it all feels just as natural. At almost no point, the calling code is even aware that it is calling one or the other because there is no difference.

That is what making “100% interoperability” a most significant playing field rule right from the beginning can do for the new modern language!

So if you’re going to design a new programming language, I suggest you consider imbuing it as one of the top priorities, as it will allow for much better adoption. And what creator of the library, tool, or language doesn’t want this kind of adoption superpower? 😉

As you could notice, Clara is not looking for an entirely radically different approach to coding, and instead, she is looking for a way to keep 75% of what is working well, and perhaps use a few more modern features of the language to improve the other 25% significantly.

This could be reducing the amount of the boilerplate by letting the language figure out the obvious so that you don’t have to specify it every time. This could also be a different decision to make everything an expression, which makes specific scenarios much more ergonomic and more comfortable to read, for example, try-catch block, where you need to set a variable in the “try” part and rethrow an enhanced error in the “catch” part.

These things and more are improving the readability significantly.

Additionally, the ability to have first-class immutable variables and nullable/non-nullable types eliminates whole classes of possible mistakes and errors. It is fantastic!

Stand on the shoulders of the giants!

Most of the modern languages are created to be used standalone, detached from the existing library and tooling ecosystem, either by design or “forced” by community guidelines or culture.

These modern languages might see some adoption, but they will eventually die out or stay in the small niche because the majority of professionals will just continue using the mature ones because they have better support for literally everything. There are rare, infrequent, exceptions from this rule.

If the new programming language wants to stay strong, it needs to stand on the shoulders of the giants.

So, instead of going against the former mature language, and doing everything differently, leverage as much as you can from the mature ecosystem, and add more value on top of that. This way, people, when learning this language don’t have to give up anything, and they only stand to gain— a real win-win situation!

Did that spike your curiosity about Kotlin?

I have written a 4-part (350-pages total) “Ultimate Tutorial: Getting Started With Kotlin” (+ more to come), and you can get it as a free bonus by becoming a member of my monthly newsletter.

On top of just Kotlin, it is full of goodies like TDD, Clean Code, Software Architecture, Business Impacts, 5 WHYs, Acceptance Criteria, Personas, and more.

—Sign up here and start learning how to build full-fledged Kotlin applications!

Thank you and ask for you!

Thank you so much for reading this article! I hope you enjoyed it. Please, tell me what you think about this in the comments!

Also, it would make me so much happier if you could share this post with your friends and colleagues who you think might benefit from it. Or you could share it on your favorite social media!

You are welcome to read my blog about Kotlin, and my blog about TDD and best software engineering practices.

And let’s connect on LinkedIn: I post short weekly updates about software developer’s productivity and happiness, teamwork, mental health, and a bit about Kotlin.

If you want to hear more of my opinions, follow me on Twitter.


cover image source: pexels