<?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 Samuel Pastva on Medium]]></title>
        <description><![CDATA[Stories by Samuel Pastva on Medium]]></description>
        <link>https://medium.com/@daemontus?source=rss-aa268da52164------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Cs3VXHmL7tpflK9Wvjqfog.png</url>
            <title>Stories by Samuel Pastva on Medium</title>
            <link>https://medium.com/@daemontus?source=rss-aa268da52164------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 03:00:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@daemontus/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[Inline traits in Kotlin]]></title>
            <link>https://medium.com/@daemontus/inline-traits-in-kotlin-ab538228a202?source=rss-aa268da52164------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab538228a202</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Samuel Pastva]]></dc:creator>
            <pubDate>Mon, 20 Feb 2017 13:54:26 GMT</pubDate>
            <atom:updated>2017-02-20T13:54:26.611Z</atom:updated>
            <content:encoded><![CDATA[<p>Writing code that is easy to understand and yet performs well is often like juggling a bunch of chainsaws on the roof of a driving car. Almost impossible. And some youtube commenter will dismiss it’s as fake anyway.</p><p>In this post, I’d like to discuss how to achieve something similar: JVM traits (interfaces, yo) with both virtual, static and even inline dispatch that can be used (apart from other useful stuff) to implement blazingly fast partial application in Kotlin.</p><blockquote>Disclaimer: This article contains claims that are based on benchmarks and claims that are based on personal preferences. The author is aware that the post-truth reality is fundamentally broken and so are benchmarks and personal preferences. If you have a suggestion on how to improve on the presented material, share it in the comments!</blockquote><h3>Let there be Traits</h3><p>Kotlin (or JVM for that matter) interfaces can only define virtual methods and have no <em>Self</em> type. This is a natural design decision for dynamic imperative languages, but it makes implementing some traditional algebraic structures rather complicated.</p><p>Lets look at addition of objects of the same type. Defining such relationship alone can be quite unintuitive:</p><pre>// First draft - let&#39;s make everything dynamic!<br>interface Additive {<br>   fun add(b: Additive): Additive<br>}</pre><pre>// Second draft - at least the argument and the result are the same<br>interface Additive {<br>   fun &lt;T : Additive&gt; add(b: T): T<br>}</pre><pre>// Is this the best we can do?<br>interface Additive&lt;A: Additive&lt;A&gt;&gt; {<br>   fun add(b: A): A<br>}</pre><p>You are cornered by the absence of the <em>Self</em> type into using an infinite type hierarchy. Ew. But this is not only ugly, it it is incomplete. Where did the zero go? Algebraically, element zero is a part of the addition relation and we can’t just leave it out. Of course, you could try this…</p><pre>interface Additive&lt;A: Additive&lt;A&gt;&gt; {<br>   val zero: A<br>   fun add(b: A): A<br>}</pre><p>But this is almost worse: Not only is zero part of each additive object, you can’t even create zero without already having some other additive object.</p><p>So how can we fix this? Well, we have to go deeper. If we can’t define addition just by specifying properties of one additive element, we have to define a whole context under which addition is allowed:</p><pre>interface Addition&lt;Item&gt; {<br>   val zero: Item<br>   infix fun Item.add(other: Item): Item<br>}</pre><pre>// standard integer addition<br>object IntAddition : Addition&lt;Int&gt; {<br>   override val zero: Int = 0<br>   override infix fun Int.add(other: Int): Int = this + other<br>}</pre><pre>// And now we can use it<br>IntAddition.run {<br>   val a = 5<br>   val b = a add 3<br>   val c = (b add zero) add a<br>}</pre><p>You can even take this a step further, and use this kind of context to implement partial application in a more concise way:</p><pre>class BoundedAddition(private val upperBound: Int) : Addition&lt;Int&gt; {<br>   override val zero: Int = 0<br>   override infix fun Int.add(other: Int): Int <br>      = if (this + other &gt; upperBound) upperBound <br>        else (this + other)<br>}<br><br>BoundedAddition(5) {<br>   val a = 3 add 5 // 5<br>}</pre><pre>BoundedAddition(10) {<br>   val a = 3 add 5 // 8<br>}</pre><p>Also note that these context can be then easily composed into larger entities:</p><pre>interface Group&lt;T&gt; : Addition&lt;T&gt;, Multiplication&lt;T&gt;</pre><h3>Boxing and Closures</h3><p>This trait/context design pattern can be useful only if it can also perform well. On JVM this brings up the issue of boxing and in Kotlin also closure inlining. Other compiled languages such as Rust and C++ solve this problem by explicitly generating and optimising each trait implementation separately. On the other hand, JVM generics and interfaces are implemented dynamically. This reduces the size of the binary (and the amount of classes), but can also cripple performance.</p><p><strong>Benchmark time!</strong> In this example, we compare a simple static function with a trait similar to the one in the previous section. All integers handled by the trait will be boxed, which should reduce the performance significantly.</p><pre>private var counter = 0<br>private fun addWithHistoryStatic(a: Int, b: Int): Int {<br>    counter += a + b<br>    return a + b + counter<br>}</pre><pre>fun benchStatic(): Long = measureNanoTime {<br>    var sum = 0<br>    for (i in 0..Int.MAX_VALUE) {<br>        sum += addWithHistoryStatic(i, 2*i)<br>    }<br>}</pre><pre>interface Adder&lt;T&gt; {<br>    fun addWithHistory(a: T, b: T): T<br>}</pre><pre>object IntAdder : Adder&lt;Int&gt; {<br>    private var counter = 0<br>    override fun addWithHistory(a: Int, b: Int): Int {<br>        counter += a + b<br>        return a + b + counter<br>    }<br>}</pre><pre>fun benchBoxing(): Long = measureNanoTime {<br>    var sum = 0<br>    IntAdder.run {<br>        for (i in 0..Int.MAX_VALUE) {<br>            sum += addWithHistory(i, 2*i)<br>        }<br>    }<br>}</pre><p>Indeed, after running both bench methods until the execution time stabilises (to remove warmup influence), we can see that <em>benchBoxing</em> takes a little over 5s, while <em>benchStatic</em> completes in ~580ms. <strong>Almost 10x faster.</strong></p><blockquote>All tests are performed on a i7–4770 using the Kotlin 1.1 RC. Unfortunately, Kotlin 1.0.6 does not have all the optimisations that make this article possible.</blockquote><h3>Inline for rescue!</h3><p>A little known feature of Kotlin inline modifier is that it can be also applied to virtual, even overriden functions. The only requirement is that the function is final. Inlining works based on the compile time type information, and hence we can use it to implement a primitive “template”.</p><p>All we have to do is update the IntAdder object, making the method final and inlined (we also have to make the counter field public, because inline methods can’t access private data):</p><pre>object IntAdder : Adder&lt;Int&gt; {<br>    @JvmField var counter = 0<br>    final inline override fun addWithHistory(a: Int, b: Int): Int {<br>        counter += a + b<br>        return a + b + counter<br>    }<br>}</pre><p><strong>With this modification, the benchmark times are now essentially equal</strong>, ~580ms both for the static method and the inlined trait.</p><p>Naturally, this speedup happens only if the type information is available at compile time. Following modification to the benchmark will get us back to the unusable speeds:</p><pre>fun benchBoxing(): Long = <em>measureNanoTime </em><strong>{<br>    </strong>val adder: Adder&lt;Int&gt; = IntAdder<br>    adder.<em>run </em><strong>{<br>        </strong>var sum = 0<br>        for (i in 0..Int.MAX_VALUE) {<br>            sum += addWithHistory(i, 2*i)<br>        }<br>    <strong>}<br>}</strong></pre><h3>Future work: mixing inlined and dynamic</h3><p>As we have seen, this kind of trickery works only when the type information is available at compile time, which is rather impractical. But fortunately, very often, you don’t care as much about the performance of the whole codebase as you care about a few specific hotspots.</p><p>Imagine you have successfully identified several hotspots in your codebase and observed that they would indeed benefit from inlining (due to boxing or other optimisations). Now imagine you could write something like this:</p><pre>inline fun &lt;reified I&gt; Adder&lt;I&gt;.dispatchInlined() {<br>    when (this) {<br>        is IntAdder -&gt; this.<em>hotspot</em>&lt;Int, IntAdder&gt;()<br>        else -&gt; this.<em>hotspot</em>&lt;I, Increment&lt;I&gt;&gt;()<br>    }<br>}</pre><pre>inline fun &lt;reified T, reified I: Adder&lt;T&gt;&gt; I.hotspot() {<br>    // some code<br>}</pre><p>In theory, this code should inline the hotspot method to a place where specific type information is available at compile time, or gracefully fall back to the dynamic behaviour. In practice, <strong>this kind of optimisation is currently not performed by the Kotlin compiler </strong>and both branches contain the same boxed virtual call.</p><p>However, assuming you are not against some ugly copy-pasting, you can inline the hotspot method manually:</p><pre>inline fun &lt;reified I&gt; Adder&lt;I&gt;.dispatchInlined() {<br>    when (this) {<br>        is IntAdder -&gt; // some code<br>        else -&gt; // some code<br>    }<br>}</pre><p>In this case, the compiler can again inline all the trait methods (however, you loose the main advantage — having one implementation for all traits).</p><h3>Conclusion</h3><p>As we have seen, the inlining system in Kotlin provides a potentially very powerful tool for code optimisation, even when the code itself is highly generic. If you want to express your support for more inline optimisations, you can follow <a href="https://youtrack.jetbrains.com/issue/KT-10403">KT-10403</a>, <a href="https://youtrack.jetbrains.com/issue/KT-12405">KT-12405</a>, <a href="https://youtrack.jetbrains.com/issue/KT-15044">KT-15044</a>, <a href="https://youtrack.jetbrains.com/issue/KT-12497">KT-12497</a>, <a href="https://youtrack.jetbrains.com/issue/KT-15997">KT-15997</a>, <a href="https://youtrack.jetbrains.com/issue/KT-15871">KT-15871</a>, <a href="https://youtrack.jetbrains.com/issue/KT-16451">KT-16451</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab538228a202" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Moto X, náhľad do budúcnosti]]></title>
            <link>https://medium.com/@daemontus/moto-x-nah-ad-do-buducnosti-693698bda6d6?source=rss-aa268da52164------2</link>
            <guid isPermaLink="false">https://medium.com/p/693698bda6d6</guid>
            <dc:creator><![CDATA[Samuel Pastva]]></dc:creator>
            <pubDate>Sat, 09 Nov 2013 00:51:42 GMT</pubDate>
            <atom:updated>2013-11-11T00:25:29.228Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_1pdngxayRG6vEwDNvY4gw.jpeg" /><figcaption>foto:theverge.com</figcaption></figure><h4>Takto vyzerá telefón ktorý si asi nikdy nekúpite, aj keď by ste mali.</h4><p>Pred pár rokmi sme úspešne napísali bodku za érou hľadania najvýkonnejšieho osobného počítača. Časy vkusne neoholených mladíkov, ktorí svoje stroje tlačia za limity fyzikálnych zákonov a termosku tekutého dusíka majú vždy po ruke, sa tak nenávratne skončili. Teraz však nastal čas zboriť ďalší berlínsky múr.</p><p>Od roku 2007 sa výrobcovia telefónov, <em>(prečo sa stále hráme na nejaké smartphony a múdre telefóny, dnes je to štandard, tak to aj štandardne nazývajme)</em> na čele s kórejskou Big Blue, predháňajú v tom, komu sa podarí vytlačiť pôsobivejšie propagačné materiály. 2.4 gigaherz, 8 jadier, 3GB ram, 4000 mAh, termoska s tekutým dusíkom v cene...</p><p>Motorola ale tento rok ukázala, akým smerom by sa mali uberať skutočné inovácie. Moto X je telefón, ktorý v každom tabuľkovom porovnávaní porážajú aj rok staré Nokie, no predsa ho užívatelia milujú. Po šiestich rokoch krutých tabuľkových vojen som sa teda rozhodol vyliezť zo zákopu a zistiť či vojna už skončila.</p><h4>Konštrukcia</h4><p>Každý telefón má svoju “dušu” ktorú cítite hneď ako ho vezmete do ruky. iPhone je elegantný a dravý, HTC je futuristické ale prívetivé, Samsung je majestátny a trochu exotický, aká je ale Moto X? Priateľská.</p><blockquote>V okamihu, keď chytíte Moto do ruky viete, že toto je telefón ktorý nebol navrhnutý aby na vás ľudia v práci závistlivo pozerali. Toto je telefón, ktorý sa má dobre držať v ruke.</blockquote><p>Tvarom a veľkosťou pripomína Moto väčšiu kocku mydla so zrezanými okrajmi. Telefón je ale navrchu o niečo hrubší, takže ťažisko je príjemne posunuté do stredu dlane. Zadná strana je navyše pokrytá matným plastom, ktorý dosť spoľahlivo odpudzuje odtlačky a na dotyk je nezvykle hebký.</p><p>Samostatná kapitola je drobná jamka na zadnej strane, do ktorej je vsadené logo Motoroly. Nie je síce presne tam, kde bude mať väčšina ľudí prst pri používaní telefónu, no ako píše jeden recenzent:</p><blockquote>Táto jamka nemá žiadny praktický význam. A predsa vždy, keď o ňu náhodou zavadíte, pocítite že takto je to správne a inak to nikdy nemohlo byť.</blockquote><p>Moto síce neohúri svojou hrúbkou, ktorá pri kamere prekračuje 10mm, no ostatnými rozmermi zadupáva konkurenciu do zeme. Extrémne tenký rámček displeja sa vyplatil a potenciálny zákazník si v podstate kupuje 4.7-palcový displej v tele 4-palcového telefónu.</p><h4>Kontextový procesor + ActiveDisplay, a.k.a. Magic Box</h4><p>Kontextový procesor je to čo robí z Moto magický telefón. Tento kúsok kremíka neustále zisťuje, čo sa s telefónom práve deje a ako na to vhodne reagovať. Spolu s aktívnym displejom, ktorý dokáže rozsvietiť len pixely ktoré sú skutočne nutné na zobrazenie informácií je to vražedná kombinácia.</p><p>Ako často vyťahujete telefón z vrecka len aby ste zistili koľko je hodín, alebo či vám niekto písal? Dvadsať, tridsať, štyridsať krát za deň? A viete čo to dá práce zobudiť celý telefón aby ste vy videli svoj čas a neprečítané maily?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*tBXCsv8auO5vNa23Rwro0g.jpeg" /><figcaption>source: <a href="http://www.droid-life.com/">http://www.droid-life.com/</a></figcaption></figure><p>Kontextový procesor túto zodpovednosť berie na seba a nie len že vám zobrazí všetky dôležité informácie bez nutnosti zobúdzať telefón, eliminuje aj nutnosť stláčať tlačidlo na odomknutie displeja.</p><blockquote>Vytiahnete telefón z vrecka a hneď vidíte novú SMS. Chytíte telefón do ruky a slide-to-unlock už vám svieti na displeji. Žiadne tlačidlá, mágia.</blockquote><p>A holubica z klobúka na záver: Chcete niečo odfotiť? Zatraste telefónom. Kým sa vám ho podarí namieriť na cieľ, fotoaparát už bude zapnutý.</p><h4>Rozpoznávanie jazyka + Google Now a.k.a. budúcnosť, skoro</h4><p>Nie len že Moto vie či leží na stole, v ruke alebo vo vrecku. Moto počúva. Moto pozná váš hlas a vie kedy ju voláte. Asi ako pes. Jediný rozdiel je v tom že váš pes pravdepodobne nepotrebuje datacentrum aby vám priniesol noviny.</p><p><em>“Ok, Google Now, what’s the time?”</em></p><p>Spomínate ako sme sa každú chvíľu pýtali na čas? A čo ak leží telefón na druhom konci miestnosti? Alebo na prístrojovej doske auta? Moto vám ho povie aj tak. Len už asi tej baterky toľko neušetríte…</p><p><em>“Ok, Google Now, remind me to call Mom when I get home.”</em></p><p>Google Now po novom podporuje tzv. lokalizované pripomienky. Neviete kedy prídete do práce, ale viete že nesmiete zabudnúť poslať email hneď ako tam budete? Google nezabudne.</p><blockquote>Google Now je jednoducho budúcnosť. Len ešte nie tak úplne.</blockquote><p>Tak aby ste nepovedali že stále len pozitívne:</p><p>Google Now potrebuje non-stop internet. Pokiaľ vám na chvíľu vypadne signál, základné príkazy ako <em>“Call …”</em> budú fungovať, ale po dlhšej dobe offline prestanú reagovať aj tie.</p><p>Napriek tomu že zobúdzanie telefónu hlasom nereaguje len tak na hocikoho, rozhodne nie je stopercentné a dovolím si tvrdiť že v miestnosti s 30 Moto X od rôznych ľudí by dobre mierené <em>“OK, Google Now”</em> zobudilo aspoň 5 z nich.</p><p>Kopa funkcií je obmedzená len na Americký trh. Nemyslím funkcie ako televízny program alebo odlety lietadiel, bez toho sa dá žiť. Prakticky ale čokoľvek čo sa týka prehrávania alebo rozpoznávania hudby na Slovensku nefunguje. Fňuk…</p><h4>Takmer čistý Android</h4><p>Moto X nie je Nexus, nemá aktualizácie systému priamo od Googlu. Moto je ale tak blízko k Nexusu ako sa len dá. Berie to najlepšie z čistého Androidu a pridáva vlastnú funkcionalitu, ktorú na rozdiel od rukou maľovaných ikoniek a možnosti zmeniť si systémový font na Comic Sans uživateľ aj ocení.</p><p>Moto Migrate: Na túto aplikáciu rýchlo zabudnete, no práve vďaka nej je k vám Moto priateľská hneď od začiatku. Žiadna zložitá synchronizácia, jednoducho nainštalujete Migrate na svoj starý telefón a všetky kontakty, históriu hovorov a správ, fotky aj hudbu máte za pár minút v novom telefóne.</p><p>Moto Assist: Automatické prepínanie na tichý mód v nočných hodinách a v časoch kedy máte naplánované dôležité udalosti v kalendári. Už žiadne trápne zvonenie telefónu na porade alebo pípanie reklamných newsletterov uprostred noci.</p><p>Driving Mode: V prípade že šoférujete a niekto vám telefonuje, miesto vyzváňania sa ozve meno volajúceho a môžete hovor rovno prijať alebo odmietnuť hlasom. Toto sa, podobne ako všetko v Moto X, zapína a vypína automaticky.</p><h4>Záverom…</h4><p>Čo viac dodať? Že napriek priemernému procesoru je načítanie webov rovnako rýchle ako na Macbooku? Že aj keď vám večer zostane 40% baterky a nie 5% ako na väčšine telefónov, aj tak ho dáte na noc nabiť? Že fotoaparát mohol mať lepšiu citlivosť v šere? Že väčšinu týchto funkcií zvládnu aj rôzne CustomROMs na vašom Nexuse? A zaujíma vás to? To patrí do tabuliek. V betónovej džugli rozhoduje o prežití niečo úplne iné.</p><p>Prečo je teda Moto telefón ktorý si nekúpite? Z veľkej časti preto lebo sa predáva len v USA, Kanade a v Puerto Ricu(wtf?!). A priznajme si to, ktorý zdravý človek by niečo takéto kupoval cez eBay (duh) keď doma môže kúpiť Nexus 4/5, HTC One alebo Galaxy S4?</p><p>Z druhej časti proste preto, lebo tabuľkové vojny síce skončili, no väčšina ľudí o tom ešte nevie. Sedia v zákopoch, chodia k svojmu mobilnému operátorovi a ukazujú prstom na makety telefónov za sklom. A na tabuľky vedľa nich.</p><p>Preto toto nie je subjektívna recenzia na telefón ktorý si 90% publika nebude vedieť zaobstarať. Toto je pripomienka pre Slovenského zákazníka že doba sa zmenila.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=693698bda6d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>