<?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 Xin on Medium]]></title>
        <description><![CDATA[Stories by Xin on Medium]]></description>
        <link>https://medium.com/@wishing129?source=rss-e9adfe0e8570------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*nEc5LxTtB4TNiF_T.jpg</url>
            <title>Stories by Xin on Medium</title>
            <link>https://medium.com/@wishing129?source=rss-e9adfe0e8570------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 13:47:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wishing129/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[Quick Guide for making your Android API Kotlin-friendly]]></title>
            <link>https://medium.com/@wishing129/quick-guide-for-making-your-android-api-kotlin-friendly-1ebd3a9eecaa?source=rss-e9adfe0e8570------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ebd3a9eecaa</guid>
            <category><![CDATA[interoperability]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Xin]]></dc:creator>
            <pubDate>Mon, 21 May 2018 05:18:47 GMT</pubDate>
            <atom:updated>2018-05-21T05:25:48.575Z</atom:updated>
            <content:encoded><![CDATA[<p>I can’t remember how many times I have attempted to get into this Kotlin hotness. All those learning attempts left me was, “no more NPEs!” (hooray but remind me how?), “more concise code!”(cool like what?), and “let/by/run/with/when/lazy, etc”(right, all the new keywords that I can’t tell apart and don’t know how to apply).</p><p>Last week at work, I had to revamp a small Java-written library, hoping to make it more friendly to Kotlin developers. Now that I am wrapping up the task, I want to share the notes I made along the way. If you have published your beautifully written Java libraries on Github, wanting more traction with Kotlin adoption, and haven’t had time to learn the full spectrum of the language, here is a quick guide for doing the job.</p><h3>@Before</h3><p>I followed the <strong>Interop Guide</strong> from <a href="https://android.github.io/kotlin-guides/interop.html">android.kotlin.io</a> and <a href="https://kotlinlang.org/docs/reference/java-interop.html">kotlinlang.org</a>. I recommend to read them for a more comprehensive view. This article will focus on 2 topics among all, and provide more explanation and examples to help those who have little Kotlin experience to understand the context.</p><h3>Nullability annotations</h3><p>Kotlin type system is aimed to eliminate NPEs. How? It requires variables to be declared with nullability. And, it throws compilation error when a nullable value gets assigned to a variable declared to be nonnull. Unfortunately, one of the few cases where a NPE can happen in Kotlin is due to interoperating with Java — non-annotated types from Java APIs are interpreted as “platform types”, which have ambiguous nullability.</p><pre>// Non-null variable<br><strong>var</strong> a: String = &quot;abc&quot; <br>a = <strong>null</strong> // compilation error</pre><pre>// Nullable variable<br><strong>var</strong> b: String? = &quot;abc&quot; <br>b = <strong>null</strong> // ok<br><strong>var</strong> len = b?.length() // referenced as b?</pre><pre>// Assuming Java API<br><strong>public</strong> Car getCarInstance() {...}<br>// When consumed in Kotlin<br><strong>var</strong> c = Car.getCarInstance() // platform type inferred<br>// How it&#39;s seen in Kotlin<br><strong>var</strong> c: Car! = Car.getCarInstance() // ! =&gt; platform type<br>// therefore<br><strong>var</strong> e: Car? = c // ok<br><strong>var</strong> d: Car = c // no compilation error, but leads to runtime risk</pre><p>While the first 2 examples demonstrated how Kotlin enforces nullability, we see compromise made in example 3 — since nullability of c is unknown, Kotlin compiler will not complain whether you assigning c to a non-null or a nullable reference. However, a runtime NPE could get thrown if Car.getCarInstance() in fact returns null and its non-null reference gets dereferenced somewhere without proper null check.</p><p>Our goal is to <strong>get rid of those “platform types”</strong>(denoted with “!”). In order to achieve that, for Java APIs that will be consumed in Kotlin, every non-primitive parameter, return, and field type should be given a nullability annotation.</p><h4>Choice of Annotation Flavors</h4><p>The @NonNull and @Nullable annotations from com.android.support:support-annotations satisfy most of our needs, e.g. params, return types.</p><pre>// Java without nullability annotations<br><strong>int</strong> startFlow(Context context, FlowParams params) {...}</pre><pre>// How it&#39;s seen in Kotlin<br><strong>fun</strong> startFlow(context: Context!, params: FlowParams!) : Int {...}</pre><pre>// Java with nullability annotations<br><strong>int</strong> startFlow(<strong>@NonNull</strong> Context context, <strong>@NonNull</strong> FlowParams params) {...}</pre><pre>// How it&#39;s seen in Kotlin<br><strong>fun</strong> startFlow(context: Context, params: FlowParams): Int {...}</pre><p>Starting from Java 8, annotating Type Parameter comes into play and further strengthens Java type checking. However, Android annotations at this point does not support Type Parameter. See why it could be a problem:</p><pre>// Java<br><strong>@Nullable</strong><br><strong>public </strong>List&lt;Car&gt; fetchCars(<strong>@Nullable</strong> Bundle bundle) {…}</pre><pre>// How it’s seen in Kotlin<br><strong>fun</strong> fetchCars(bundle: Bundle?) : MutableList&lt;Car!&gt;? {…}</pre><p><em>MutableList&lt;Car!&gt;?</em> indicates that Kotlin compiler is aware that the returned list is nullable, however, it does not know whether Car objects inside of the list are nullable. There is the risk of assigning a null Car object to a non-null Kotlin variable and things burst at runtime.</p><p>JetBrains annotations org.jetbrains:annotations:15+ supports annotation on type parameters, meaning we can apply annotations to the function signature like this:</p><pre>// Java<br><strong>@Nullable</strong><br><strong>public</strong> List&lt;<strong>@NonNull</strong> Car&gt; fetchCars(<strong>@Nullable</strong> Bundle bundle) {…}</pre><pre>// How it’s seen in Kotlin<br><strong>fun</strong> fetchCars(bundle: Bundle?) : MutableList&lt;Car&gt;? {…}</pre><p>The exclamation mark disappears!</p><p>Again, it’s a Java 8 feature. From your project module settings, you will have to set the source and target compatibility to 1.8 before you can use this language feature. And if you haven’t migrated to Android gradle plugin 3.0+, well, do that first because enabling Java 8 requires it.</p><p>For my project, I decided to stick with Android annotations from support library, due to the following considerations:</p><ul><li>Android lint checker works only with the support library annotations.</li><li>I want to be able to use other Android specific annotations that JetBrains doesn’t support, e.g. threads, resources, etc., while having 2 types of annotation systems doesn’t seem clean.</li><li>In the specific APIs that I work on, the object in collection is never null given current implementation.</li></ul><h3>Lambda parameters</h3><p>SAM(Single Abstract Method) Java interfaces can be written as lambdas when passed into function calls as parameters in Kotlin. If it’s placed at last, the function call can then use trailing-lambda syntax, as demonstrated below.</p><pre>// Java API<br>public void doSomething(String code, Runnable runnable) {...}</pre><pre>// Consumed in Kotlin<br>doSomething(code, () -&gt; Unit)</pre><pre>// Consumed in Kotlin, trailing-lambda syntax<br>doSomething(code) {<br>  () -&gt; Unit<br>}</pre><h4>SAM Java interfaces</h4><p>In Android, one typical scenario is passing a listener to a function call for asynchronous processing. I examined all the listener interfaces and methods where the listeners are passed in in the library I worked on, gladly found out that most of the listeners are eligible for SAM conversion and that they are placed at last. Following is an example of how it leads to nice and clean Kotlin code.</p><pre>// Java: method signature<br><strong>public</strong> void makeRequest(@Nullable String type, @NonNull ResponseListener listener);</pre><pre>// Kotlin: calling the method with an anonymous class<br>requestClient.makeRequest(&quot;someType&quot;, object : ResponseListener {<br>  <strong>override</strong> <strong>fun</strong> onResponse(responseCode: Int, resultList: MutableList&lt;Car&gt;?) {<br>    print(responseCode)<br>  }<br>})</pre><pre>// Kotlin: because ResponseListener is eligible for SAM conversion // and placed at last, it can also be written as below - shortened // and easier to read<br>requestClient.makeRequest(&quot;someType&quot;) {<br>  responseCode, resultList -&gt; print(responseCode)<br>}</pre><h4>Multi-method Java interfaces</h4><p>What if an interface has multiple methods?</p><p>Inspired by <a href="https://github.com/android/android-ktx/blob/master/src/main/java/androidx/core/animation/Animator.kt">android-ktx</a>, with the help of Kotlin extension functions, we can have a more idiomatic way of calling <em>connect(..)</em> in Kotlin.</p><pre>// == Kotlin consumption ==<br>// instead of<br>requestClient.connect(object: ClientStateListener {<br>  <strong>override</strong> <strong>fun</strong> onSetupFinished(responseCode: Int){<br>    print(responseCode)<br>  }<br>  <strong>override</strong> <strong>fun</strong> onDisconnected() {<br>    print(“Disconnected!”)<br>  }<br>}</pre><pre>// == Kotlin consumption ==<br>// now with the extension function<br>requestClient.connect(<br>  onSetupFinished = {<br>    print(responseCode)<br>  },<br>  onDisconnected = {<br>    print(“Disconnected!”)<br>  }<br>)</pre><p>In Kotlin, functions are first-class citizens that can be assigned to variables, passed as arguments or returned from another function. In the lower part of the code block above, 2 function literals get passed to function <em>connect(..)</em>. Named arguments is another convenient feature that Kotlin supports — by specifying <em>onSetupFinished</em> and <em>onDisconnected</em> when passing in function literals, it avoids mixing the two.</p><p>And here is how we made <em>RequestClient.connect(..)</em> take 2 function literals instead of an instance of <em>ClientStateListener</em> — we added an extension function which overloads the existing <em>connect(..)</em>. The implementation of the new <em>connect(..)</em> basically takes the function literals, construct a <em>ClientStateListener</em>, and pass it to the original method. Receiver of the extension function is <em>RequestClient</em>.</p><pre>// Kotlin extension to RequestClient<br><strong>fun</strong> RequestClient.connect(<br>  onSetupFinished: (responseCode: Int) -&gt; Unit,<br>  onDisconnected: () -&gt; Unit) {<br>    <strong>var</strong> listener = object: ClientStateListener {<br>      <strong>override</strong> <strong>fun</strong> onSetupFinished(responseCode: Int) {<br>        onSetupFinished.invoke(responseCode)<br>      }<br>      <strong>override</strong> <strong>fun</strong> onDisconnected() {<br>        onDisconnected.invoke()<br>      }<br>  }<br>  connect(listener)<br>}</pre><p>I placed the extended function in a <em>.kt</em> file, under the same package of <em>RequestClient</em>. Android Studio automatically detects Kotlin file and prompts you with setting up for compiling Kotlin. It adds change in your <em>build.gradle</em> to include Kotlin stdlib and relevant plugins.</p><h3>Others</h3><p>You should avoid using Kotlin hard keywords for your public method name, to name a few, by/let/when/lazy. Use “bean”-style setter/getters for methods to be accessed as properties. Be mindful of operator overloading. etc. The Interop Guide is your friend!</p><h3>@After</h3><p>Revamping an existing Java API for Kotlin consumption points directly to the differences between the two languages. It has given me a pretty awesome angle to get to know Kotlin as a Java developer.</p><p>Hopefully this was helpful!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*6BWlE2EiyBajyRL3GPym5A.jpeg" /><figcaption>Tolorange ~ by Francois Angers</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ebd3a9eecaa" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>