DEV Community

Zuhaib Ahmad
Zuhaib Ahmad

Posted on • Originally published at zuhaibahmad.com on

4

Pythonic Imports in Kotlin

If you have been working with Kotlin for some time now, you might have encountered issues with name conflicts with Kotlin’s reserved keywords. A common example is with the popular mocking library Mockito, where the when method which is now used by Kotlin for its switch-like construct. So you end up doing something like this:

`when`(messenger.getMessage()).thenReturn("Hello World!")
Enter fullscreen mode Exit fullscreen mode

Another scenario is when you want to name the imported class or extension function something more meaningful and readable. Which can be acheived to some extent with the use of a typealias. However, there’s a better solution available right into the Kotlin standard library.

Pythonic Way of Handling Imports

One the most flexible things I find in Python is the ability to name the imported classes almost anything you want, just like a variable. So you would simply import a class with a name that suits your style e.g.

import matplotlib.pyplot as plt
Enter fullscreen mode Exit fullscreen mode

Now, you can use plt as a variable throughout your script.

Kotlin’s Import-As Alias

I wished to have this for Android development after I ran into some ambiguity issues with a recent project. Upon some searching, I was surprized to find that Kotlin had this feature all along. Just like Python, you can simply add imports with an as keyword.

Let’s look at how our Mockito problem is resolved now:

import org.mockito.Mockito.`when` as whenever
Enter fullscreen mode Exit fullscreen mode

You can now use whenever in place of the less pleasant 'when' througout the class.

whenever(messenger.getMessage()).thenReturn("Hello World!")
Enter fullscreen mode Exit fullscreen mode

So that was it. Another reason to love Kotlin (and Python as well)! ;)


For suggestions and queries, just contact me.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay