<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sergey Ryabov on Medium]]></title>
        <description><![CDATA[Stories by Sergey Ryabov on Medium]]></description>
        <link>https://medium.com/@colriot?source=rss-db53bf377423------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9AppiB_MfMUunfm35YK_lQ.png</url>
            <title>Stories by Sergey Ryabov on Medium</title>
            <link>https://medium.com/@colriot?source=rss-db53bf377423------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 04:27:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@colriot/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Writing Java-friendly Kotlin code]]></title>
            <link>https://medium.com/android-news/writing-java-friendly-kotlin-code-c408b24fb4e?source=rss-db53bf377423------2</link>
            <guid isPermaLink="false">https://medium.com/p/c408b24fb4e</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[interoperability]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Sergey Ryabov]]></dc:creator>
            <pubDate>Mon, 24 Jul 2017 14:43:52 GMT</pubDate>
            <atom:updated>2017-08-22T14:02:57.836Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S1GQ8XNnwIZHEBmzpYtnbw.png" /></figure><p>While Kotlin becomes more and more popular, a lot of Java libraries are getting Kotlin helpers to make their usage from Kotlin code more idiomatic and clean. People, who’ve already tried Kotlin, understand that this language is much more pleasant to write code in than Java. So, wouldn’t it be cool to write libraries in Kotlin in the first place? Using all its niceties, while still keep being Java-friendly on the caller side? This is possible, and in this post I’ll give you some tips on how to achieve it.</p><p>One of the main selling sides of Kotlin is its stunning Java interoperability. It’s indeed very easy to call Java code from Kotlin, however, the opposite has its pitfalls. But Kotlin creators have something to our aid.</p><blockquote>In this post I’ll talk only in the context of Kotlin’s JVM backend.</blockquote><h3>Statics, @JvmStatic</h3><p>Let’s consider an Analytics library we’re writing. We’ve designed the main interaction point as an object:</p><pre>object Analytics {<br>  fun init() {...}<br>  fun send(event: Event) {...}<br>  fun close() {...}<br>}</pre><p>On Kotlin call-site it looks great, simply:</p><pre>Analytics.<em>send</em>(Event(&quot;custom_event&quot;))</pre><p>But from Java we must do:</p><pre>Analytics.<strong><em>INSTANCE</em></strong>.<em>send</em>(new Event(&quot;custom_event&quot;));</pre><p>Can we make the Java code look the same as Kotlin’s? Yes, we can. Simply mark all our public methods as @JvmStatic and they will be compiled as static Java methods:</p><pre>object Analytics {<br> <strong> @JvmStatic </strong>fun init() {...}<br>  <strong>@JvmStatic</strong> fun send(event: Event) {...}<br>  <strong>@JvmStatic</strong> fun close() {...}<br>}</pre><pre>...<br>// Java call-site<br>Analytics.<em>send</em>(new Event(&quot;custom_event&quot;));</pre><p>If we also have any public properties in the object, they should be marked @JvmStatic as well — while backing fields are static by default, we still need to modify getters and setters:</p><pre><strong>@JvmStatic</strong> var isInited: Boolean = false<br>private set</pre><h3>Default parameters, @JvmOverloads</h3><p>At the same time, our Event class looks like:</p><pre>data class Event(val name: String, val context: Map&lt;String, Any&gt; = <br>  <em>emptyMap</em>())</pre><p>We set a default value for context because we want to be able to create a marker Event without any data. Getters and setters with proper naming will be conveniently generated for us. And we may expect two constructors to be generated as well: one that takes name and another that takes name and context. Indeed, two constructors will be generated, but not the ones we expect. One will be a full constructor, and the other will be a synthetic full constructor with an additional bit-flag parameter to configure, whether other parameters have non-default explicit values set or not. Luckily, the latter won’t be accessible from Java. Of course, we can use a full constructor everywhere in Java, but can’t we do better? Definitely! We can force generating overloading constructors by annotating the primary constructor with @JvmOverloads:</p><pre>data class Event <strong>@JvmOverloads constructor</strong>(val name: String, val context: Map&lt;String, Any&gt; = <em>emptyMap</em>())</pre><p>This will create the two constructors that we had originally expected. We also can use this trick for functions with default parameters which may be called from Java.</p><h3>Checked exceptions, @Throws</h3><p>At some point of time we decide to add an ability to use plugins with our Analytics.</p><pre>interface Plugin {<br>  fun init()<br>  <em>/** </em><strong><em>@throws </em></strong><em>IOException if sending failed */<br>  </em>fun send(event: Event)<br>  fun close()<br>}</pre><p>We design it a way that all plugins are handled in one place, and send may throw an IOException, which will be handled in the main library class and logged:</p><pre>// object Analytics<br>@JvmStatic fun send(event: Event) {<br>  log(&quot;&lt;Internal Send event&gt;&quot;)<br><br>  plugins.<em>forEach </em>{<strong> <br>    </strong>try {<br>      it.<strong>send</strong>(event)<br>    } catch (<strong>e: IOException</strong>) {<br>      log(&quot;WARN: ${it.<em>javaClass</em>.<em>simpleName</em>} fired IOE&quot;)<br>    } <br>  }<strong><br></strong>}</pre><p>There is no need to <a href="https://kotlinlang.org/docs/reference/exceptions.html#checked-exceptions">declare any thrown exception</a> in a Kotlin method signature, and it’s cool. But here comes the Java — one of our library’s consumers decides to write his own plugin in Java, properly throws an IOException where it’s needed, adds throws part in the signature and sees a compiler error:</p><pre><em>Overridden method does not throw IOException</em></pre><p>We don’t want to make our consumers unhappy. Sadly, Java still has checked exceptions, and they must be stated in a method’s signature. For that specific case, Kotlin has @Throws. Marking our method with this annotation and including all thrown exception classes as its parameters will solve the problem:</p><pre>interface Plugin {<br>  fun init()<br>  <em>/** @throws</em><strong><em> </em></strong><em>IOException if sending failed */</em><br>  <strong>@Throws(IOException::class)</strong><br>  fun send(event: Event)<br>  fun close()<br>}</pre><h3>Java names, @JvmName</h3><h4>Properties</h4><p>Now we have plugins and we want to have an ability to check if any are installed. Let’s add a property like this:</p><pre>val hasPlugins get() = plugins.<em>isNotEmpty</em>()</pre><p>We know that Kotlin respects Java Bean naming conventions, so any property called name will turn into getName()/setName() methods pair (for var case). Also we know that if the property is called isName, it will turn into isName()/setName() pair. It’s really great, this helps us on the Java-caller side!</p><p>But what about our hasPlugins property? Obviously, it will turn into getHasPlugins() method which is ugly. Wouldn’t it be better to call it hasPlugins()? Again, Kotlin has a solution for this — @JvmName annotation, and since we need to rename the getter, this annotation should be applied to the getter itself:</p><pre>val hasPlugins <strong>@JvmName(&quot;hasPlugins&quot;)</strong> get() = plugins.<em>isNotEmpty</em>()</pre><p>or alternatively (by specifying target in the annotation itself):</p><pre>@<strong>get:</strong>JvmName(&quot;hasPlugins&quot;) val hasPlugins get() = <br>  plugins.<em>isNotEmpty</em>()</pre><p>But this is not the only possible application of @JvmName.</p><h4>Functions</h4><p>Next one — generics erasure problem.</p><p>It’s very common for a library to have some Utils classes. Which in Kotlin almost always turns into extension functions. Let’s say our utils have these couple of methods:</p><pre>fun List&lt;Int&gt;.printReversedSum() {<br>  <em>println</em>(this.<em>foldRight</em>(0) { it, acc -&gt; it + acc })<br>}<br><br>fun List&lt;String&gt;.printReversedSum() {<br>  <em>println</em>(this.<em>foldRight</em>(StringBuilder()) {<br>    it, acc -&gt; acc.append(it)<br>  })<br>}</pre><p>In the bytecode both will have the same signature due to erasure:</p><pre>public static final void printReversedSum(@NotNull <strong>List</strong> $receiver)</pre><p>We can fix that using the same annotation:</p><pre>fun List&lt;Int&gt;.printReversedSum() {<br>  <em>println</em>(this.<em>foldRight</em>(0) { it, acc -&gt; it + acc })<br>}</pre><pre><strong>@JvmName(&quot;printReversedConcatenation&quot;)</strong><br>fun List&lt;String&gt;.printReversedSum() {<br>  <em>println</em>(this.<em>foldRight</em>(StringBuilder()) {<br>    it, acc -&gt; acc.append(it)<br>  })<br>}</pre><blockquote>NOTE! It is not only needed for Java-callers, but it actually fixes a compiler error. Since all Kotlin code turns into the same JVM bytecode as the Java code itself, you’ll get a collision at the bytecode level, and this code simply won’t compile.</blockquote><h4>Files</h4><p>As far as we know, extension functions file will turn into a class with static methods in the bytecode. Therefore, we won’t feel much difference in their usage from Java. Except one — this class will be named for the enclosing file with the suffix Kt. For example, the following file</p><pre>//reverser.kt</pre><pre>package util</pre><pre>fun String.reverse() = StringBuilder(this).reverse().toString()</pre><p>will turn into ReverserKt class. Let’s rename it to something more meaningful for Java usage, like ReverserUtils. Easy:</p><pre>//reverser.kt<br><strong>@file:JvmName(&quot;ReverserUtils&quot;)</strong></pre><pre>package util</pre><pre>fun String.reverse() = StringBuilder(this).reverse().toString()</pre><p>By specifying this familiar annotation before package declaration and with proper annotation target, we make our Java-caller code look better.</p><h3>@JvmMultifileClass</h3><p>The last @JvmName use case often goes along with @JvmMultifileClass. If we’ll use the same @file:JvmName in several files of the same package, trying to make their content accessible from the same JVM class, we’ll need @file:JvmMultifileClass in each of these files. Otherwise, several JVM classes with the same full classname will be generated, which won’t compile. Here is the example from Kotlin Stdlib:</p><pre><strong>//Collections.kt</strong><br>@file:kotlin.jvm.JvmMultifileClass<br>@file:kotlin.jvm.JvmName(&quot;CollectionsKt&quot;)<br><br>package kotlin.collections</pre><pre>-----</pre><pre><strong>//Iterables.kt</strong><br>@file:kotlin.jvm.JvmMultifileClass<br>@file:kotlin.jvm.JvmName(&quot;CollectionsKt&quot;)<br>package kotlin.collections</pre><h3><strong>Constants, @JvmField</strong></h3><p>If our library’s public API includes any constants, we may expose them to Java in several ways:</p><ul><li>const — essentially creates a constant, no accessors. Only works for top-level or object-level primitives and Strings.</li><li>@JvmField — makes a backing field accessible on its own, with no accessors. Works with vars as well.</li></ul><p>For all object properties with backing fields these fields are generated as statics on an enclosing class level, which essentially makes them public static fields.</p><blockquote>NOTE! Declaring an object property as lateinit also makes its backing field public (while keeping all accessors), which may not be what you want for a public API, so pay attention.</blockquote><h3>Generics , @JvmWildcard, @JvmSuppressWildcards</h3><p>We know that Kotlin has <a href="https://kotlinlang.org/docs/reference/generics.html#declaration-site-variance">declaration-site variance</a> in its toolbox. This means that List&lt;Dog&gt; can finally be used in place of List&lt;Animal&gt; without any wildcard magic, no more &lt;? extends …&gt; or &lt;? super …&gt;. But in Java we have only use-site variance and Kotlin has to deal with that. So, what happens for List&lt;out E&gt;?</p><p>In the case of the incoming parameters,</p><pre>fun addPlugins(plugs: List&lt;Plugin&gt;)</pre><p>will be turned into</p><pre>public final void addPlugins(@NotNull List&lt;<strong>? extends </strong>Plugin&gt; plugs)</pre><p>to let one easily pass collections of Plugin’s successors. Because it’s the common case for incoming parameters handling in Java. If we want to suppress the use of wildcards, we should declare the method like one of the following:</p><pre>// Suppress only for this param.<br>fun addPlugins(plugs: List&lt;<strong>@JvmSuppressWildcards</strong> Plugin&gt;)</pre><pre>// Suppress for the whole method.<br><strong>@JvmSuppressWildcards</strong> fun addPlugins(plugs: List&lt;Plugin&gt;)</pre><pre>// Or even for the whole class.<br><strong>@JvmSuppressWildcards</strong><br>object Analytics {<br>  fun addPlugins(plugs: List&lt;Plugin&gt;)<br>}</pre><p>But in the case of the return value</p><pre>fun getPlugins(): List&lt;Plugin&gt;</pre><p>there will be no wildcards</p><pre>public final List&lt;Plugin&gt; getPlugins()</pre><p>Because it’s a common case in Java as well, and otherwise one’ll need to handle wildcards by hand.</p><p>If we do need wildcards in return values, we can use the following option</p><pre>fun getPlugins(): List&lt;<strong>@JvmWildcard</strong> Plugin&gt;</pre><p>and it will turn into</p><pre>public final List&lt;<strong>? extends</strong> Plugin&gt; getPlugins()</pre><p>For example, if we want to prevent adding new Plugins to the returned collection at the compile-time (<em>better also do a </em><strong><em>defensive</em></strong><em> copy in that case, because </em><em>plugins field is backed by </em><em>ArrayList</em>).</p><blockquote>NOTE! In case of a <a href="https://kotlinlang.org/docs/reference/generics.html#declaration-site-variance">contravariant</a> type parameter <strong>in </strong>with modifier, like in Comparable&lt;<strong>in</strong> T&gt;, wildcards will be generated as&lt;? super …&gt;.</blockquote><h3>Working with java.lang.Class</h3><p>If we’ll also need to handle a bit of reflection in our library, most probably, we will want to support both Class&lt;?&gt; and KClass&lt;*&gt;. And there is actually no need to implement these separately — we can convert from one to another quite easily with these built-in extension properties:</p><pre>val &lt;T&gt; KClass&lt;T&gt;.<strong><em>java</em></strong>: Class&lt;T&gt;<br>// and <br>val &lt;T : Any&gt; Class&lt;T&gt;.<strong><em>kotlin</em></strong>: KClass&lt;T&gt;</pre><p>For example, we’re building a Kotlin version of <a href="https://github.com/square/retrofit">Retrofit</a>, and we have a method for constructing actual REST API interface implementation which looks like:</p><pre>fun &lt;T: Any&gt; create(service: <strong>KClass&lt;T&gt;</strong>): T</pre><p>Then the corresponding method for Java’s Class&lt;?&gt; will be the following:</p><pre>fun &lt;T: Any&gt; create(service: <strong>Class&lt;T&gt;</strong>): T {<br>    return create(service.<strong><em>kotlin</em></strong>)<br>}</pre><h3>Builders</h3><p>Usually, in Kotlin there is no such thing as builders, because we have default and named parameters and <a href="https://kotlinlang.org/docs/reference/idioms.html#builder-style-usage-of-methods-that-return-unit">apply</a> function. But for better Java usage, we may consider implementing one. With our simplified Retrofit it may look like this:</p><pre>class Builder {<br>  private <strong>lateinit</strong> var baseUrl: String<br>  private var client: Client <strong>= Client()</strong><br><br>  fun baseUrl(baseUrl: String) = <strong>this</strong>.<em>also </em>{ it.baseUrl = baseUrl }<strong><br><br>  </strong>fun client(client: Client) = <strong>this</strong>.<em>also </em>{ it.client = client }<strong><br><br>  </strong>fun build() = Retrofit(baseUrl, client)<br>}</pre><p>For required parameters we can use lateinit modifier, for others — just set the default values. Besides that, to eliminate all the return this from every setter, we can use my favorite <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/also.html">also</a> or <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/apply.html">apply</a>. Pretty concise, isn’t it?</p><h3>Internal visibility</h3><p>We also need to pay attention to members with internal visibility. In bytecode they will turn into publics, but with long ugly names (not so ugly in the actual library jar, though). It was done, because there is no internal visibility in Java, and one should not call them unintentionally. Let’s consider our Retrofit example:</p><pre>// Retrofit.kt<br>internal fun validate(): Retrofit</pre><pre>......</pre><pre>// When linking lib as a separate module with sources. <br>// IntelliJ <em>won&#39;t let you compile</em>.</pre><pre>final Retrofit retrofit =<br>    new Retrofit.Builder()<br>        .baseUrl(&quot;https://api.domain.com&quot;)<br>        .client(new Client())<br>        .build()<br>        .validate<strong>$production_sources_for_module_library_main</strong>();</pre><pre>......</pre><pre>// When linking lib as a JAR file. <em>Compiles successfully</em>.</pre><pre>final Retrofit retrofit =<br>    new Retrofit.Builder()<br>        .baseUrl(&quot;https://api.domain.com&quot;)<br>        .client(new Client())<br>        .build()<br>        .validate<strong>$library_main</strong>();</pre><p>As we can see, one is still able to call them, that’s why we should not use internal for any essential code that is not supposed to be a public API.</p><h3>Null-checks</h3><p>It’s good to know that the bytecode of our Kotlin lib will be augmented with</p><ul><li>@Nonnull and @Nullable annotations reflecting actual Kotlin types</li><li>null-checks for all nonnull parameters and return values in the public API</li></ul><p>The former will help our consumers while coding in IDE, the latter will catch incorrect behavior at runtime.</p><blockquote>It may happen that you used to use compiler flags -Xno-param-assertions and -Xno-call-assertions to turn off generating runtime null-checks (for example, because you’re 100% Kotlin and you’re paranoid about the performance overhead of these checks on Android). In that case, you should make sure that these flags are not used for the library compilation.</blockquote><h3>Inline functions</h3><p>Inline functions will be accessible in Java as usual methods. Of course, they won’t be inlined by the compiler :)</p><p>At the same time, inline functions with reified type parameters won’t be visible in Java at all, because without actual inlining they won’t work.</p><h3>Unit</h3><p>If we have functions with the lambdas returning Unit, we’ll force our Java consumers to deal with it. Because Unit, similar to Void, is an actual type, and Java compiler will require such lambda values to have an actual return statement. I know, this sucks:</p><pre>ReverserUtils.<em>forEachReversed</em>(list, it -&gt; {<br>  System.<em>out</em>.println(it);<br>  <strong>return null;</strong><br>});</pre><h3>Typealiases</h3><p>It’s simple here: no typealiases are accessible from Java. Not a big deal though, actual types are still there, and Java users are already used to long type names with enclosing generics.</p><p>Hopefully, this post will help you to perform more seamless migration to Kotlin in your Java codebases, and also will help to broaden your Kotlin’s usage to writing useful open-source libraries, while not forcing you to abandon all the Java/Groovy/Closure/etc. users.</p><p>Don’t forget to check out:</p><ul><li><a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.jvm/index.html">Kotlin API docs for used annotations</a></li><li><a href="https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html">Kotlin Lang reference section about Interop</a></li><li><a href="https://github.com/colriot/post-java-fiendly-kotlin">Sample code from this post</a></li></ul><p>If you’re not very comfortable with Kotlin, I suggest to check these also:</p><ul><li><a href="http://kotl.in/">Kotlin Portal</a>. The main url to remember — all you need to learn Kotlin</li><li><a href="https://kotlinlang.org/docs/reference">Kotlin Lang full reference</a></li><li><a href="https://try.kotlinlang.org/">Try Kotlin online</a>. Online IDE with exercises</li><li><a href="https://kotlinlang.org/docs/tutorials/koans.html">Kotlin Koans</a></li><li><a href="https://www.manning.com/books/kotlin-in-action">Kotlin in Action</a>. A book by Kotlin team members Dmitry Jemerov and Svetlana Isakova</li><li><a href="https://leanpub.com/kotlin-for-android-developers">Kotlin for Android Developers</a>. A book by Antonio Leiva</li></ul><p>This article was initially prepared for <a href="https://sdjournal.org/writing-java-friendly-kotlin-code/">SDJournal</a>. I’d like to thank its team for proofreading the article.</p><p><em>Thank you for reading and please tap the ❤</em><strong><em> </em></strong><em>button</em><strong><em> </em></strong><em>if you liked it. You can also follow me on </em><a href="https://twitter.com/colriot"><em>Twitter</em></a><em>. Happy coding!</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F3e491f%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F3e491f%2F&amp;image=http%3A%2F%2Fapi.screenshotlayer.com%2Fapi%2Fcapture%3Faccess_key%3Dfe59908dad3baab69ffab249a2224b03%26viewport%3D1024x612%26width%3D1000%26url%3Dhttps%253A%252F%252Fupscri.be%252F3e491f%253Fscreenshot&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href">https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c408b24fb4e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/writing-java-friendly-kotlin-code-c408b24fb4e">Writing Java-friendly Kotlin code</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>