<?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 Gaetan Zoritchak on Medium]]></title>
        <description><![CDATA[Stories by Gaetan Zoritchak on Medium]]></description>
        <link>https://medium.com/@gz_k?source=rss-36cd1b73c9ab------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lEqIL-LtT1t3TxB1RBlNUQ.jpeg</url>
            <title>Stories by Gaetan Zoritchak on Medium</title>
            <link>https://medium.com/@gz_k?source=rss-36cd1b73c9ab------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 13:10:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gz_k/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[Compose pour iOS]]></title>
            <link>https://medium.com/@gz_k/compose-pour-ios-b251ccf1c1f8?source=rss-36cd1b73c9ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/b251ccf1c1f8</guid>
            <dc:creator><![CDATA[Gaetan Zoritchak]]></dc:creator>
            <pubDate>Fri, 12 May 2023 08:31:18 GMT</pubDate>
            <atom:updated>2023-05-12T09:19:08.788Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VasNbDp9J_V-D9znFhqcug.jpeg" /></figure><p>Une des annonces majeure de la dernière Kotlin conf est la <strong>sortie de Compose pour iOS en version alpha</strong>. Il est désormais possible de développer une application mobile complète avec une seule base de code Kotlin.</p><p>Quelques explications!</p><p><strong>Kotlin et le multi-plateforme</strong></p><p>Depuis la version 1.3 de Kotlin, il est possible d’écrire du code Kotlin et de le compiler pour différentes plateformes. En plus de la JVM (serveur ou Android), on peut déployer dans un navigateur (transpilation JavaScript) ou en code natif (linux, Windows, Mac, iOS). De nombreuses compagnies utilisent ce mécanisme pour partager une partie importante du code de leurs applications mobiles (Deezer, CashApp, PlanGrid…).</p><p><strong>Jetpack Compose</strong></p><p>Ce framework annoncé en 2017 par Google est le standard de développement des applications sous Android. Fortement influencé par React il met en œuvre des mécanismes de séparation d’un état d’une application avec son rendu visuel.</p><p><strong>Compose multiplatform (Desktop)</strong></p><p>En collaboration avec Google, JetBrains a fourni la version multi-platforme de Compose en ajoutant le desktop. Ainsi le code UI d’une application Android est réutilisable pour avoir la version de l’application sur Windows, Mac et Linux.</p><p><strong>Compose for iOS</strong></p><p>L’annonce faite lors de KotlinConf 2023 est l’arrivée de Compose sur iOS. Concrètement, cela veut dire que le code UI créé pour Android est utilisable tel quel pour déployer la version iPhone d’une app.</p><p>D’un point de vue technique, JetBrains reprends les composants bas niveau de Jetpack Compose pour en fournir une version iOS. L’intégration est réalisé en dessinant les composants graphiques sur des canvas. JetBrains travaille à reprendre toute la physique des iPhones pour fournir la même expérience utilisateur (vitesse de scrolling, …).</p><p>La démonstration que nous avons pu voir est convaincante. L’approche de JetBrains est comme toujours de favoriser l’interopérabilité.</p><p>Il est ainsi possible de mixer des composants de chaque plateforme avec le code partagé:</p><ul><li>une application iOS peut prendre des composants développés en Compose</li><li>une application Compose for iOS peut intégrer des composants iOS</li></ul><p>La version alpha indique que JetBrains est toujours en train de travailler à l’amélioration du produit.</p><p>Sur la partie performance, ils cherchent à garantir du 60 FPS ou 120 FPS selon l’appareil.</p><p>Les premiers tests semblent leur donner raison (<a href="https://twitter.com/QamarSafadi/status/1655297313701609475">voir le tweet de QamarSafadi cf vidéo ci-dessous</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*0CXUEo4p1tRfqni485C1gA.gif" /></figure><p>C’est une approche à laquelle nous croyons depuis longtemps. Notre librairie Charts.kt permet de déployer des charts réalisés en Kotlin dans des applications iOS (entre autres), avec ou sans Compose.</p><p>Et vous, êtes vous prêt à utiliser Compose pour iOS ? Dans de nouvelles applications full Compose ou en intégrant des portions de Compose dans des applications existantes?</p><p>Si vous avez des besoins pour réaliser des graphiques en tout genre, sur mobile, desktop ou web, sans prise de tête, n’hésitez pas à découvrir <a href="https://charts-kt.io/">Charts-kt.io</a> et nous contacter.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b251ccf1c1f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One Kotlin team for all your mobile apps?]]></title>
            <link>https://medium.com/@gz_k/one-kotlin-team-for-all-your-mobile-apps-318db0a212f4?source=rss-36cd1b73c9ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/318db0a212f4</guid>
            <category><![CDATA[multiplatform]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Gaetan Zoritchak]]></dc:creator>
            <pubDate>Thu, 27 Jan 2022 15:20:42 GMT</pubDate>
            <atom:updated>2022-01-27T15:32:21.495Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R3NGagxeTyaOBNipCloKPA.png" /></figure><p><em>Until now, mobile applications required specialized developers on </em><strong><em>Android</em></strong><em> AND </em><strong><em>iOS</em></strong><em>. Developing the same mobile application for each platform consisted of duplicating the code and the teams. The latest advances in the Kotlin ecosystem allow us to envision another future. Indeed, at the end of January 2022, some observant developers noticed </em><a href="https://github.com/JetBrains/compose-jb/blob/6da56d56ea7ee745cf64d65cb6108d562d78a579/experimental/examples/falling-balls-mpp/build.gradle.kts#L56-L81"><em>exciting changes</em></a><em> on </em><strong><em>JetBrains’ Compose Multiplatform project</em></strong><em>. What is it, and what are the impacts on mobile applications development?</em></p><p>More than ten years after the launch of the iPhone and Android, the two operating systems share the entire smartphone market. The global distribution, one-third of iPhones for two-thirds of Android, prevents skipping over a platform. Therefore, the creators of mobile applications must offer their applications in two versions: one for iOS and the other for Android.</p><p>The languages ​​and development environments for each platform are very different.</p><p>At the beginning of Android, developers had to use Java. However, since 2019, <a href="https://developer.android.com/kotlin/first">Google has recommended using <strong>Kotlin</strong> to develop Android applications</a>.</p><p>On iOS, the language used when the iPhone was launched was Objective-C. Apple has since replaced it with <strong>Swift</strong>, which has many similarities to Kotlin.</p><h3>Cross-platform Kotlin code</h3><p>Kotlin has the particularity of being able to be cross-platform. It is possible to compile the same code for different runtime environments:</p><ul><li>JVM and Android,</li><li>JavaScript,</li><li>Native for use in C or Objective-C contexts.</li></ul><p>This feature makes it possible to <strong>integrate Kotlin code into applications for iOS</strong> in the form of Xcode frameworks. This first step made it possible to limit the duplication of the code of the mobile applications. The common application core, written in Kotlin, was shared by Android and iOS.</p><p>This approach has been implemented in recent years by the mobile teams of major companies such as Netflix, Philips, Leroy Merlin, Yandex (<a href="https://kotlinlang.org/lp/mobile/case-studies/">cf. KMM case study</a>).</p><p>However, the shared code in mobile applications was limited to the business part of the code until now. In particular, the creation of user interfaces, dependent on APIs specific to each platform, could not be carried out via common code. This UI code, which often represents 30% of the code of a mobile application, prevented complete reuse of the Kotlin code.</p><h3>Google Jetpack Compose</h3><p>The novelty comes from a framework started in 2017 by Google: <a href="https://developer.android.com/jetpack/compose"><strong>Jetpack Compose</strong></a>. It is a toolkit that proposes a new way of building user interfaces entirely based on code (previously, developers used XML files to define the user interface).</p><p>After four years of work, <strong>Google delivered version 1.0 of Jetpack Compose in July 2021</strong>.</p><p>JetBrains, the company behind the Kotlin language, <strong>has extended Google’s framework to make it cross-platform</strong>. JetBrains released version 1.0 of <a href="https://blog.jetbrains.com/kotlin/2021/12/compose-multiplatform-1-0-is-going-live/">Compose Multiplatform</a> in December 2021. It allows you to produce a Desktop (Windows, Mac, Linux) and/or Web (JavaScript) application.</p><p>Concretely, the code of an Android application, defining the interface and the behavior, can be directly used to produce an application installed on a Windows, Mac, or Linux workstation.</p><p>The great novelty of the last few days is the possibility of <strong>deploying a Compose Multiplatform application on iOS</strong>.</p><p>JetBrains will probably first deliver this new feature with an experimental status, the time to test and refine the framework. But, we can be sure that, before long, <strong>it will be possible to write a cross-platform application entirely in Kotlin and deploy it on Android and iOS</strong>.</p><h3>What impacts on existing projects and teams?</h3><p>For existing mobile projects, it may have no impact. Applications with large codebases will have no interest in re-writing their code with this new framework.</p><p>On the other hand, a new Android project, written in Kotlin with the Jetpack Compose toolkit, can be deployed tomorrow in an iPhone for a minimal cost. This is an opportunity for companies that cannot afford specialists for each mobile platform.</p><p>I am personally convinced that this new proposal will seduce many companies. The only question is, «what will be the proportion of full Kotlin mobile applications in the future?».</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=318db0a212f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin 1.2 est arrivé]]></title>
            <link>https://medium.com/@gz_k/kotlin-1-2-est-arriv%C3%A9-542381fe901c?source=rss-36cd1b73c9ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/542381fe901c</guid>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Gaetan Zoritchak]]></dc:creator>
            <pubDate>Tue, 28 Nov 2017 16:14:04 GMT</pubDate>
            <atom:updated>2017-11-28T18:25:41.907Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Cet article est la traduction du </em></strong><a href="https://blog.jetbrains.com/kotlin/2017/11/kotlin-1-2-released/"><strong><em>post officiel de Jetbrains</em></strong></a><strong><em> (à leur demande). Quand il est indiqué «nous», il s’agit de Jetbrains ;-).</em></strong></p><p>Nous publions aujourd’hui Kotlin 1.2. C’est une nouvelle version majeure et une grande avancée vers notre objectif de permettre l’utilisation de Kotlin dans tous les composants d’une application moderne.</p><p>Avec Kotlin 1.1, nous fournissions le support officiel de <strong>Javascript comme cible de déploiement</strong>, permettant ainsi de compiler Kotlin en JS pour une exécution dans le navigateur. Avec Kotlin 1.2, nous ajoutons la possibilité de <strong>partager le code entre la JVM et Javascript</strong>. Vous pouvez désormais écrire une seule fois la logique métier de votre application et la réutiliser dans toutes les couches de votre application — le backend, un navigateur frontend et une application mobile Android. Nous travaillons également sur des librairies favorisant la réutilisation du code, comme une librairie cross-platform de sérialisation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*Xpia5UxkKjuCsbp3CwyLmw.png" /></figure><p>Kotlin 1.2 est inclus dans <a href="https://www.jetbrains.com/idea/">IntelliJ IDEA 2017.3</a> (également publié cette semaine). Si vous utilisez Android Studio ou une version précédente d’Intellij IDEA, vous pouvez installer la nouvelle version depuis la fenêtre de dialogue disponible sous <em>Tools | Kotlin | Configure Kotlin Plugin Updates</em>.</p><p>Cette version s’appuie sur de nombreuses contributions extérieures, et nous remercions toutes les personnes qui ont transmis des retours, créé des bugs, et tout spécialement celles qui ont soumis des pull requests.</p><h4>Projets Multiplatforme</h4><p>Un projet multiplatforme vous permet de construire plusieurs couches de votre application — backend, frontend et App Android — depuis la même base de code. Ce type de projet contient à la fois des <strong>modules <em>communs</em></strong>, qui contiennent du code indépendant de la plateforme, et des <strong>modules <em>plateformes</em></strong>, qui contiennent le code spécifique à une plateforme (JVM ou JS) et peuvent utiliser des librairies de cette plateforme. Pour appeler du code <em>plateforme</em> depuis un module <em>commun</em>, vous pouvez ajouter la déclaration <strong>expected</strong> — tous les modules plateformes devront alors fournir une implémentation <strong>actual</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jak-2p9khwd90Oqd4RMSag.png" /></figure><p>Pour plus d’information sur cette fonctionnalité, merci de vous référer à la <a href="http://kotlinlang.org/docs/reference/multiplatform.html">documentation</a>.</p><p>Nous travaillons également sur une série de librairies communes pour vous permettre de déplacer plus de code vers des modules communs:</p><ul><li><a href="http://kotlinlang.org/api/latest/kotlin.test/index.html">kotlin.test</a>, inclus par défaut dans Kotlin 1.2, vous permet d’écrire vos tests une seule fois et de les exécuter à la fois dans la JVM et en JS;</li><li><a href="https://github.com/kotlin/kotlinx.html">kotlinx.html</a> supporte un rendu <strong>isomorphique </strong>— le même code produit du HTML en backend et en frontend;</li><li><a href="https://github.com/kotlin/kotlinx.serialization">kotlinx.serialization</a> permet de facilement sérialiser vos objets Kotlin entre les différentes couches de votre application, en utilisant JSON ou ProtoBuf comme format de sérialisation.</li></ul><h4>Performances de compilation</h4><p>Durant le développement de la 1.2, nous avons beaucoup travaillé à optimiser les performances du compilateur. Nous avons déjà amélioré les temps de compilation de 25% par rapport à Kotlin 1.1, et nous envisageons d’autres améliorations significatives qui seront livrées lors de mises à jour 1.2.x.</p><p>Le graphique ci-dessous montre la baisse du temps de compilation de deux projets importants de Jetbrains construits avec Kotlin:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dtHKquS0AJiCJJJJ5UjUrg.png" /></figure><h4>Autres améliorations du langage et de la librairie</h4><p>Nous avons également réalisé des améliorations ciblées du langage et de la librairie standard:</p><ul><li><a href="http://kotlinlang.org/docs/reference/whatsnew12.html#array-literals-in-annotations">Une syntaxe plus concise</a> pour transmettre plusieurs paramètres à une annotation (array literals);</li></ul><p>Le support de <em>lateinit</em> sur les propriétés top-level et les variables locales, ainsi que la vérification de l’initialisation effective d’une variable <em>lateinit</em>;</p><ul><li><a href="http://kotlinlang.org/docs/reference/whatsnew12.html#smart-cast-improvements">Des smart casts plus évolués</a> et <a href="http://kotlinlang.org/docs/reference/whatsnew12.html#information-from-explicit-casts-is-used-for-type-inference">une amélioration de l’inférence de type</a> dans certains cas;</li><li>La compatibilité de la librairie standard avec les restrictions de séparation de package introduites par Java 9;</li><li>Un nouveau package kotlin.math dans la librairie standard;</li><li>De nouvelles fonctions dans la librairie standard pour travailler avec les séquences et les collections, comprenant notamment une <a href="http://kotlinlang.org/docs/reference/whatsnew12.html#windowed-chunked-zipwithnext">série de fonctions</a> pour séparer une collection ou une séquence en plusieurs groupes de taille définie.</li></ul><p>Pour plus d’information et d’exemples de code, merci de vous référer à la page de la documentation <a href="http://kotlinlang.org/docs/reference/whatsnew12.html">What’s New in Kotlin 1.2</a>.</p><h3>Kotlin de par le monde</h3><p>Depuis la publication de Kotlin 1.1 en mars de cette année, l’adoption de Kotlin a connu une croissance très importante dans le monde. Le point culminant de cette année a été <a href="https://kotlinconf.com/">KotlinConf</a>, notre première conférence internationale, avec environ 1200 participants se rassemblant à San Francisco les 2 et 3 novembre. Nous avons enregistré toutes les présentations, et les vidéos sont disponibles sur le site de la conférence.</p><p>Kotlin est désormais un langage officiellement supporté pour le développement Android, avec un support inclus dans Android Studio 3.0, ainsi que des <a href="https://developer.android.com/samples/index.html?language=kotlin">exemples</a> officiels et un <a href="https://android.github.io/kotlin-guides/">guide de style de code</a> publié par Google. Résultat : Kotlin est déjà utilisé dans <a href="https://android-developers.googleblog.com/2017/11/update-on-kotlin-for-android.html">plus de 17% des projets sous Android Studio 3.0</a>, dont les apps des startups les plus actives et des entreprises du palmarès<em> Fortune 500</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IlSOm17Q3tQ8ZKXenOZP5A.png" /></figure><p>Du côté serveur, Spring Framework 5.0 a été publié avec de <a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/languages.html#kotlin">nombreuses fonctionnalités de support de Kotlin</a>, et Vert.x supporte Kotlin depuis la publication de la version 3.4.0. Par ailleurs, Gradle est désormais fourni avec le support d’un DSL Kotlin, et le <a href="https://github.com/gradle/kotlin-dsl">Gradle Kotlin DSL project</a> s’approche rapidement de la publication de sa version 1.0.</p><p>Le nombre de lignes de code open-source en Kotlin sur GitHub dépasse désormais 25 millions. Sur StackOverflow, Kotlin est à la fois <a href="https://stackoverflow.blog/2017/10/31/disliked-programming-languages/">l’un des langages qui présente la plus grande progression et le moins d’opposition</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BzM8HobZtITXzgW_tKvt3w.png" /></figure><p>La communauté grandissante autour de Kotlin est également étonnante. Il existe plus de 100 groupes utilisateurs dans le monde, et tant de présentations que nous avons du mal à garder la trace de toutes — mais pour celles dont nous avons la connaissance, la <a href="http://kotlinlang.org/community/talks.html">carte des présentations</a> vous donne une très bonne idée de la diffusion très large de Kotlin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QFQQyzBCw8A5O40ymSvVMg.png" /></figure><p>Pour ceux qui commencent juste leur apprentissage de Kotlin, il existe un nombre croissant de <a href="http://kotlinlang.org/docs/books.html">livres</a> (incluant notre propre “Kotlin in Action”, maintenant disponible en <a href="https://manning.com/books/kotlin-in-action">Anglais</a>, <a href="https://dmkpress.com/catalog/computer/programming/java/978-5-97060-497-7/">Russ</a>e, <a href="https://www.amazon.co.jp/Kotlin%E3%82%A4%E3%83%B3%E3%83%BB%E3%82%A2%E3%82%AF%E3%82%B7%E3%83%A7%E3%83%B3-Dmitry-Jemerov/dp/4839961743/ref=sr_1_2?ie=UTF8&amp;qid=1511539431&amp;sr=8-2&amp;keywords=kotlin">Japonais</a>, <a href="https://www.amazon.com/Kotlin%E5%AE%9E%E6%88%98-Svetlana-Isakova-Dmitry-Jemerov/dp/B07568C58F/ref=sr_1_3?s=books&amp;ie=UTF8&amp;qid=1511539582&amp;sr=1-3">Chinois</a> et <a href="https://novatec.com.br/livros/kotlin-em-acao/">Portugais</a>), de cours en ligne, de tutoriels et d’autres ressources.</p><h3>Discutez avec l’équipe</h3><p>Pour partager avec vous plus d’information sur cette nouvelle version, nous prévoyons d’animer <a href="https://info.jetbrains.com/Kotlin-Webinar-December2017.html">un webinar sur les projets multiplateforme avec Kotlin 1.2</a> le 7 décembre 18 CET. Inscrivez-vous, les places sont limitées.</p><p>L’équipe Kotlin mènera également un AMA (Ask Me Anything) sur le <a href="https://www.reddit.com/r/Kotlin/">Reddit Kotlin </a>le 5 décembre. Nous commencerons à midi CET, et serons présents pour vous répondre durant les 24 heures qui suivront.</p><h3>Comment passer à kotlin 1.2</h3><p>Comme toujours, vous pouvez <strong>essayer Kotlin en ligne</strong> at <a href="http://try.kotlinlang.org/">try.kotlinlang.org</a>.</p><ul><li><strong>Sous Maven, Gradle et npm</strong>: Utilisez 1.2.0 comme numéro de version pour le compilateur et la librairie standard. Accédez à la documentation <a href="http://kotlinlang.org/docs/reference/using-gradle.html">ici</a>.</li><li><strong>Sous IntelliJ IDEA</strong>: la version 2017.3 contient Kotlin 1.2. Pour les versions précédentes installez ou mettez à jour le plugin Kotlin plugin à la version 1.2.</li><li><strong>Sous Android Studio</strong>: Installez ou mettez à jour le plugin depuis <em>Plugin Manager</em>.</li><li><strong>Sous Eclipse</strong>: installez le plugin en utilisant <a href="https://marketplace.eclipse.org/content/kotlin-plugin-eclipse">Marketplace</a>.</li><li><strong>Le compilateur en ligne de commande </strong>peut être téléchargé depuis <a href="https://github.com/JetBrains/kotlin/releases/tag/v1.2">la page Github de la version</a>.</li></ul><p><strong>Compatibilité</strong>. En Kotlin 1.2 le langage et la librairie standard assurent la <a href="http://kotlinlang.org/docs/reference/compatibility.html">compatibilité ascendante (modulo les bugs)</a>: tout ce qui compilait et s’exécutait en versions 1.0 et 1.1 continuera de fonctionner avec la version 1.2. Pour aider les équipes de taille importante à effectuer la mise à jour de leur code progressivement, nous fournissons des options de compilateur qui désactivent les nouvelles fonctionnalités. <a href="http://kotlinlang.org/docs/reference/compatibility.html#binary-compatibility-warnings">Voici un document</a> qui couvre les écueils possible.</p><p><em>Have a nice Kotlin!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=542381fe901c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Effective tool chain for kotlin js testing]]></title>
            <link>https://medium.com/@gz_k/effective-tool-chain-for-kotlin-js-testing-b243449e8a16?source=rss-36cd1b73c9ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/b243449e8a16</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[gradle]]></category>
            <dc:creator><![CDATA[Gaetan Zoritchak]]></dc:creator>
            <pubDate>Fri, 22 Sep 2017 12:53:19 GMT</pubDate>
            <atom:updated>2017-09-27T23:42:10.842Z</atom:updated>
            <content:encoded><![CDATA[<p>Coding in kotlin and targeting javascript platform is a bit strange. Half of the tools you need are written in java or kotlin (but ran in a JVM). The other half comes from the javascript frenetic ecosystem. <br>How can we combine these tools to pick the best of the two worlds? In this post I’m going to share my choices for kotlin-js development and detail the testing part. My goals are to:</p><ol><li>Have an effective development workflow</li><li>Easily manage browsers tests</li><li>Use automated build compatibles with continuous integration.</li></ol><p>When choosing my tools I generally try to use a best-of-breed approach, using each tool for what it was designed, and trying to take the best one.</p><p>Here is the big picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*tnxxmAfJEZf_qyAgzaHGfg.png" /></figure><p>This tool chain will be part of my live <a href="https://kotlinconf.com/speakers/#speaker=gaetan-zoritchak">session at KotlinConf the 2nd of november 2017</a>.</p><p>I created a <a href="https://github.com/gzoritchak/kotlin-js-gradle-demo">github repository as a support for this post</a>. Just clone it locally and run gradlew build to test the concepts presented here.</p><h3>Gradle</h3><p>There are few build systems compatible with kotlin development. The mains ones are maven, gradle and kobalt. I generally keep maven for simple builds. Gradle is more powerful but more difficult to manage. I didn’t run enough tests on kobalt for now.</p><p>Both maven and gradle have kotlin plugins maintained by Jetbrain team.</p><p>The main reasons for choosing gradle for kotlin-js development are:</p><ol><li>JetBrains seems to have a faster pace development on gradle plugins: Dead Code Elimination is currently only available on gradle. The kotlin javascript incremental compilation will also be delivered first on gradle.</li><li>It’s really fast. Gradle has a mechanism that only re-launch the needed tasks. With the continuous mode it allows you to work on your sources, having gradle rebuilding in background only what is needed for your project.</li></ol><p>The kotlin2js plugin usage is straightforward. You don’t have to configure it a lot. One of the most important parameter is the <a href="http://kotlinlang.org/docs/reference/js-modules.html">module kind</a> which defines how the generated javascript files can be used. The default is plainbut my default choice is umd (Unified Module Definitions) which is compatible with node.js (common.js), require.js and fallbacks to plain.</p><pre>apply <strong>plugin</strong>: <strong>&#39;kotlin2js&#39;</strong></pre><pre>compileKotlin2Js {<br>    kotlinOptions{<strong><br>        </strong>moduleKind = <strong>&#39;umd&#39;<br>    </strong>}<br>}</pre><p>For your tests on your project you must add a dependency on kotlin-test-js.</p><pre>dependencies {<br>   testCompile <strong>&quot;org.jetbrains.kotlin:kotlin-test-js:</strong>$kotlin_version<strong>&quot;<br>   </strong>compile <strong>&quot;org.jetbrains.kotlin:kotlin-stdlib-js:</strong>$kotlin_version<strong>&quot;<br></strong>}</pre><p>This dependency will provide you the annotation @Test and some assertions functions.</p><pre>import kotlin.test.* </pre><pre>class SimpleTest {     <br>   @Test fun testFoo() {<br>        assertEquals(10, foo())    <br>}</pre><p>During kotlin2js compilation the annotation will be used to generate javascript code compatible with the main javascript testing frameworks: jasmine, jest, qunit, mocha, tape.</p><p>After the compilation task you have to move in the javascript world. Your code is now compiled in two javascript modules : one for your main code and the other one for test code. To execute the test module on your main module you now need to use a javascript testing framework.</p><h3>Mocha</h3><p>I didn’t take a long time to choose the testing framework. The main features of these javascript frameworks are not used during kotlin js development. Your tests are written in kotlin with a basic common denominator. The testing framework is just used as a runtime execution and report tool. You can’t use the specificities of the framework.</p><p>I took this list to check the current solutions:</p><p><a href="https://www.slant.co/topics/1489/~javascript-unit-testing-tools">Slant - 12 best JavaScript unit testing tools as of 2017</a></p><p>During my evaluation I find that mocha had a good report rendering and it was enough for me.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CCaOAHr8JvrYqMrPuH2PvA.png" /><figcaption>Terminal rendering of mocha tests.</figcaption></figure><h3>Karma</h3><p>When you plan to have your code running inside browsers it is really interesting to test it inside <strong>different</strong> browsers. This is the job of karma. It provides you a runtime environment to run your test code.</p><p>The configuration file allows you to define the locally installed browsers on which the code should be ran: chrome, safari, firefox, internet explorer, …</p><pre>module.exports = <strong>function</strong>(config) {<br>  config.set({<br>    browsers : [&#39;Chrome&#39;, &#39;Firefox&#39;]<br>  });<br>};</pre><p>It can also run your code on PhantomJs, the headless browser which is useful for automated builds.</p><p>Okay, we now have our code transpiled in javascript, we have chosen the frameworks. How can we assemble all that?</p><h3>Yarn</h3><p>The bridge between our main build script (gradle) and the javascript runtime will be done with a gradle plugin: the <a href="https://github.com/srs/gradle-node-plugin">gradle-node-plugin</a></p><blockquote>This plugin enabled you to use a lot of <a href="https://nodejs.org/">NodeJS</a>-based technologies as part of your build without having NodeJS installed locally on your system. It integrates the following NodeJS-based system with Gradle:</blockquote><blockquote><a href="https://nodejs.org/">NodeJS</a></blockquote><blockquote><a href="https://yarnpkg.com/">Yarn</a></blockquote><blockquote><a href="https://gruntjs.com/">Grunt</a></blockquote><blockquote><a href="https://gulpjs.com/">Gulp</a></blockquote><p>From this quick documentation, we have to make some decisions. NodeJS and NPM defined a way of managing javascript dependencies and scripts through a package.json file. The newcomer tool, <em>Yarn</em>, uses this file with a better strategy to manage dependencies with a local cache making it a lot more performant. As the gradle-node-plugin allows us to use it, it will be our choice.</p><p>To use the plugin in gradle we add:</p><pre>apply <strong>plugin</strong>: <strong>&#39;com.moowork.node&#39;<br></strong>node {<br>    download = <strong>true<br></strong>}<br>task yarnInstall(<strong>type</strong>: YarnTask) {<br>    args = [<strong>&#39;install&#39;</strong>]<br>}</pre><p>Yarn will be automatically downloaded during the first launch of gradle build.</p><p>We add the task yarnInstall which will execute the command yarn install. Yarn uses the default package.json configuration file to install locally all the needed tools : karma, mocha, …</p><p>The last task of our gradle build is :</p><pre>task runKarma(<strong>type</strong>: YarnTask, <strong>dependsOn</strong>: [populateNodeModules, yarnInstall]) {<br>    args = [<strong>&#39;test&#39;</strong>]<br>}<br><br>test.dependsOn runKarma</pre><p>The command yarn test rely on the testscript defined in <a href="https://github.com/gzoritchak/kotlin-js-gradle-demo/blob/master/package.json#L12">the package.json file</a>:</p><pre><strong>&quot;scripts&quot;</strong>: {<br>  <strong>&quot;test&quot;</strong>: <strong>&quot;karma start&quot;<br></strong>}</pre><p>Again, using default configuration files, we don’t have to provide any argument. When starting, karma looks for a karma.conf.jswhere the launched test configuration is defined.</p><p>The complete tool is efficient. I usually have gradle running in continuous mode on the project I’m working on. It allows to have a really quick feedback on my code.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F1tchTMxIwgA%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D1tchTMxIwgA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F1tchTMxIwgA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec9d18ac1cb60ed14fe2c04061d94136/href">https://medium.com/media/ec9d18ac1cb60ed14fe2c04061d94136/href</a></iframe><h3>Conclusion</h3><p>Testing is only a part of kotlin-js development workflow. There are other issues with other solutions. I will present most of them during my live <a href="https://kotlinconf.com/speakers/#speaker=gaetan-zoritchak">session at KotlinConf the 2nd of november 2017</a>.</p><p>If you want to have a look to a more complex kotlin build, you can star and follow our <a href="https://github.com/data2viz/data2viz">data2viz project on github</a>. Our goal is to provide a “d3js like” multiplatform library. We will soon have kotlin multiplatform builds.</p><p>Don’t hesitate to share your point of view, correct me or ask questions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b243449e8a16" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin 1.1 : JavaScript, Coroutines, et plus…]]></title>
            <link>https://medium.com/@gz_k/kotlin-1-1-javascript-coroutines-et-plus-ce2eb3d7004?source=rss-36cd1b73c9ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce2eb3d7004</guid>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Gaetan Zoritchak]]></dc:creator>
            <pubDate>Wed, 01 Mar 2017 14:13:57 GMT</pubDate>
            <atom:updated>2017-03-01T18:11:07.825Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Cet article est la traduction du </em></strong><a href="https://blog.jetbrains.com/kotlin/2017/03/kotlin-1-1/"><strong><em>post officiel de Jetbrains</em></strong></a><strong><em>. Quand il est indiqué «nous», il s’agit de Jetbrains ;-).</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*24wiqqPRLNJQKQ3ucvBHXA.png" /></figure><p>Aujourd’hui nous livrons Kotlin 1.1. C’est un grand pas en avant qui permet l’utilisation de Kotlin dans de nombreux nouveaux scénarios et nous espérons que vous l’apprécierez.</p><p>Notre vision pour Kotlin est d’offrir un unique langage expressif, performant et fortement typé pour tous les composants des applications modernes. Kotlin 1.1 réalise deux pas importants dans cette direction.</p><p>Tout d’abord, la compilation en JavaScript n’est plus expérimentale et supporte toutes les fonctionnalités du langage, une part importante de la librairie standard, ainsi que l’interopérabilité JavaScript. Vous pouvez ainsi migrer vos applications frontend web en Kotlin, tout en continuant à utiliser les frameworks JavaScript modernes tels que React.</p><p>Nous introduisons dans cette version les <strong>coroutines</strong>. Ces alternatives légères aux threads permettent des applications backends beaucoup plus scalables, en autorisant des charges très importantes sur une instance unique de JVM. Les coroutines sont également un outil très expressif pour implémenter des mécanismes asynchrones, ce qui s’avère important pour construire des interfaces réactives sur toutes les plateformes.</p><p>Nous détaillons ci-dessous plus en détail ces deux changements. Parmi les autres nouveautés se trouvent : les <a href="https://kotlinlang.org/docs/reference/whatsnew11.html#type-aliases">alias de type</a>, les <a href="https://kotlinlang.org/docs/reference/whatsnew11.html#bound-callable-references"><em>bound callable reference</em></a> , la <a href="https://kotlinlang.org/docs/reference/whatsnew11.html#destructuring-in-lambdas">déstructuration des lambdas</a>. La liste entière se trouve sur notre page <a href="https://kotlinlang.org/docs/reference/whatsnew11.html">What’s new</a> (jetez un coup d’œil aux exemples exécutables!).</p><h3>Coroutines</h3><p>Les coroutines de Kotlin rendent le code asynchrone non bloquant aussi simple que du code synchrone.</p><p>La programmation asynchrone se développe énormément dans le monde informatique. La seule chose qui la limite est la complexité considérable ajoutée à nos systèmes par ce type de programmation. Kotlin offre désormais un moyen pour maîtriser cette complexité en faisant des coroutines un outil de premier ordre dans le langage à travers l’unique concept des <strong><em>suspending functions</em></strong>. Une telle fonction (ou lambda) représente un traitement qui peut être suspendu (sans blocage de thread) et repris plus tard.</p><p>Techniquement, les coroutines sont une implémentation très légère de multitâche coopératif (très semblables aux <a href="https://fr.wikipedia.org/wiki/Fibre_(informatique)">fibres</a>). Elles agissent comme des threads fortement améliorés: quasiment pas de coût au démarrage, extrêmement bon marché à suspendre (la suspension est l’équivalent pour les coroutines du blocage pour les threads), très faciles à composer et à personnaliser.</p><p>Nous avons conçu les coroutines pour un maximum de flexibilité. L’impact au sein du langage est très faible. L’essentiel est réalisé sous forme de bibliothèques. Le projet <a href="https://github.com/Kotlin/kotlinx.coroutines">kotlinx.coroutines</a> comprend des bibliothèques pour Rx, CompletableFuture, NIO, JavaFx et Swing. Des bibliothèques similaires peuvent être écrites pour Android et JavaScript. De nombreuses constructions intégrées dans d’autres langages peuvent désormais être exprimées sous forme de bibliothèques Kotlin. Cela inclut generators/yield de Python, channel/select de Go et async/await de C#:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b399a9554da1b6938e301165bc13fb8c/href">https://medium.com/media/b399a9554da1b6938e301165bc13fb8c/href</a></iframe><p>Vous trouverez plus de détail dans <a href="https://kotlinlang.org/docs/reference/coroutines.html">la documentation</a>.</p><p><strong>Note importante</strong>. Malgré tous leurs avantages, les coroutines Kotlin sont d’une conception assez nouvelle. Elle a besoin d’essais approfondis et réels avant de garantir son exactitude et sa complétude. C’est pourquoi nous la publions sous un drapeau “opt-in” expérimental. Les règles dans le langage ne devraient pas changer, mais les API peuvent nécessiter certains ajustements en Kotlin 1.2.</p><h3>Le support de JavaScript</h3><p>Comme indiqué précédemment, toutes les fonctionnalités du langage y compris les coroutines sont disponibles à la fois sous JVM/Android et JavaScript. La réflexion en JavaScript n’existe pas encore mais nous sommes en train d’y travailler. Cela signifie qu’une application Web peut être entièrement écrite en Kotlin. Nous l’avons expérimenté avec succès chez Jetbrains. Nous publierons prochainement des tutoriels et d’autres éléments à ce sujet.</p><p>Kotlin pour JavaScript possède des types dynamiques pour interagir avec le code JavaScript «natif». Pour utiliser les librairies JavaScript reconnues à travers des API fortement typées, vous pouvez vous appuyer sur <a href="http://github.com/kotlin/ts2kt">ts2kt converter</a> avec des en-têtes de <a href="http://github.com/DefinitelyTyped/DefinitelyTyped">DefinitelyTyped</a>.</p><p>Nous supportons à la fois Node.js et le navigateur. La librairie standard est disponible à travers npm.</p><p>Plus de détail dans notre <a href="https://kotlinlang.org/docs/reference/js-overview.html">documentation</a>.</p><h3>Outillage</h3><p>Kotlin 1.1 n’est pas une version majeure pour l’outillage. Nous préférons livrer les fonctionnalités d’outillage dès qu’elles sont prêtes dans la mesure où elles n’affectent pas ou ne dépendent pas du langage. C’est ainsi que vous avez vu de nombreuses améliorations dans les versions Kotlin 1.0.x.</p><p>Pour mettre en évidence quelques-unes:</p><ul><li>Plugins Kotlin pour tous les IDE principaux: IntelliJ IDEA, Android Studio, Eclipse et NetBeans</li><li>Compilation incrémentale dans IntelliJ IDEA et Gradle</li><li>Plugins de compilation pour Spring, JPA et Mockito (rendant les classes ouvertes et générant des constructeurs sans arg)</li><li>Kapt pour le traitement des annotations</li><li>Support de Lint pour les projets Android</li><li>Nombreuses intentions IDE, inspections, corrections rapides, refactorings et améliorations de code</li></ul><p>Nous allons continuer de travailler pour rendre nos outils encore mieux et livrer les mises à jour dans les versions 1.1.x.</p><h3>La première année de Kotlin: Adoption et communauté</h3><p>Kotlin grandit. Plus de 160 000 personnes l’ont utilisé au cours de la dernière année. Les projets OSS sur Github sont passés de 2.4M à 10M lignes de code Kotlin (x4). Notre communauté Slack est passée de 1&#39;400 à plus de 5&#39;700 personnes (plus de x4). De nombreuses rencontres et groupes d’utilisateurs sont organisés par la communauté du monde entier. Nous voyons de plus en plus de livres et de cours en ligne de Kotlin publiés.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zlyuSJDDW62b4_S-n13KHA.png" /></figure><p>Kotlin est autant utilisé sous Android qu’en développement serveur. Nous observons une base utilisateur répartie à environ 50/50. Spring Framework 5.0 a introduit le support Kotlin, ainsi que Vert.x 3.4. Gradle et TeamCity utilisent Kotlin pour les scripts de construction. D’autres projets utilisant Kotlin peuvent être trouvés sur <a href="http://kotlin.link/">kotlin.link</a>.</p><p>Beaucoup d’entreprises renommées utilisent Kotlin en production: <a href="https://github.com/awslabs/serverless-photo-recognition">Amazon Web Services</a>, <a href="https://www.youtube.com/watch?v=mDpnc45WwlI">Pinterest</a>, <a href="https://building.coursera.org/blog/2016/03/16/becoming-bilingual-coursera/">Coursera</a>, <a href="https://twitter.com/robspieldenner/status/708355228832178176">Netflix</a>, <a href="https://www.reddit.com/r/androiddev/comments/5sihp0/2017_whos_using_kotlin/ddfmkf7/">Uber</a>, <a href="https://github.com/square/sqldelight">Square</a>, <a href="https://twitter.com/danlew42/status/809065097339564032">Trello</a>, <a href="https://m.signalvnoise.com/some-of-my-favorite-kotlin-features-that-we-use-a-lot-in-basecamp-5ac9d6cea95">Basecamp</a> et bien d’autres. <a href="https://github.com/corda/corda">Corda</a>, un livre distribué développé par un consortium de banques connues (comme Goldman Sachs, Wells Fargo, J.P. Morgan, Deutsche Bank, UBS, HSBC, BNP Paribas, Société Générale), a plus de 90% de Kotlin dans sa base de code.</p><p>Nous sommes reconnaissants à tous nos utilisateurs, contributeurs et défenseurs dans toutes les parties du monde. Votre soutien est très important pour nous!</p><h4>Organize your own Kotlin 1.1 Event</h4><p>Kotlin 1.1 est une bonne raison pour une rencontre d’utilisateur locaux et d’amis. Nous avons préparer des éléments de support pour vous aider à organiser un évènement de ce type. Le 23 mars nous organiserons une session live avec les membres de l’équipe Kotlin. Il existe également un pack organisateur. Plus d’info et <a href="https://docs.google.com/forms/d/e/1FAIpQLSf6iXcrIpaNIqeeUJI2L6pntS5yy_iI01PbrO9gTMmX0kg5Lw/viewform">enregistrez votre évènement ici</a>.</p><h3>La suite</h3><p>Pour faire de Kotlin un langage véritablement full-stack, nous allons fournir l’outillage et le support du langage pour compiler le même code pour plusieurs plates-formes. Cela facilitera le partage des modules entre le client et le serveur. Nous continuerons à améliorer l’outillage JavaScript et le support des bibliothèques. Entre autres choses, nous travaillons déjà sur la la compilation incrémentale pour JavaScript. Restez à l’écoute des mises à jour 1.1.x.</p><p>Java 9 est bientôt disponible. Nous fournirons le support de ses nouvelles fonctionnalités avant sa sortie.</p><p>Nous espérons obtenir beaucoup de retours sur les coroutines au cours des prochains mois. L’amélioration de cette section du langage (en termes de performance et de fonctionnalité) fait partie de nos priorités.</p><p>À part cela, notre prochaine version sera principalement axée sur la maintenance, les améliorations de performance, l’infrastructure et la correction de bug.</p><p>P.S. L’exécution du code sur plusieurs plates-formes est une axe stratégique pour Kotlin. Avec la version 1.1, nous pouvons fonctionner sur des serveurs, des ordinateurs de bureau, des appareils Android et des navigateurs. Mais à l’avenir nous allons compiler Kotlin en code natif pour l’exécuter sur beaucoup plus de plates-formes (y compris, par exemple, iOS et les périphériques embarqués). Une excellente équipe, chez JetBrains, travaille sur ce projet. Nous espérons vous montrer quelque chose d’intéressant bientôt. Cela ne vise cependant aucune version particulière.</p><h3>Instructions d’installation</h3><p>Comme toujours, vous pouvez <strong>essayer Kotlin en ligne</strong> sur <a href="http://try.kotlinlang.org/">try.kotlinlang.org</a>.</p><p><strong>Sous Maven/Gradle</strong>: Utilisez 1.1.0 comme numéro de version pour le compilateur et la librairie standard. Voir la documentation <a href="https://kotlinlang.org/docs/reference/using-gradle.html">ici</a>.</p><p><strong>Dans IntelliJ IDEA</strong>: 2017.1 dispose de Kotlin 1.1 inclus, pour les versions précédentes installez ou mettez à jour le plugin Kotlin à la version 1.1.</p><p><strong>Dans Android Studio</strong>: installez ou mettez à jour le plugin via le <em>Plugin Manager</em>.</p><p><strong>Dans Eclipse</strong>: installez le plugin par le <a href="https://marketplace.eclipse.org/content/kotlin-plugin-eclipse">Marketplace</a>.</p><p><strong>Le compilateur en ligne de commande </strong>peut être téléchargé depuis la <a href="https://github.com/JetBrains/kotlin/releases/tag/v1.1">page Github de la version 1.1</a>.</p><p><strong>Compatibilité</strong>. La compatibilité ascendante est respectée en Kotlin 1.1 (pour le langage et la bibliothèque standard): du code compilé et exécuté en 1.0 continuera à fonctionner en 1.1. Pour aider les grandes équipes qui mettent à à jour progressivement leur code, nous fournissons un commutateur de compilation qui désactive les nouvelles fonctionnalités. <a href="https://kotlinlang.org/docs/reference/compatibility.html#binary-compatibility-warnings">Voici un document</a> qui couvre les scénarios courants et les pièges possibles.</p><p><em>Have a nice Kotlin!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce2eb3d7004" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scale out PI computation with kotlin coroutines]]></title>
            <link>https://medium.com/@gz_k/scale-out-pi-computation-with-kotlin-coroutines-4ee3ad294674?source=rss-36cd1b73c9ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ee3ad294674</guid>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Gaetan Zoritchak]]></dc:creator>
            <pubDate>Mon, 20 Feb 2017 09:35:37 GMT</pubDate>
            <atom:updated>2017-02-20T09:35:37.684Z</atom:updated>
            <content:encoded><![CDATA[<p>Kotlin 1.1 brings some interesting new features. Among them, <strong>Kotlin coroutines </strong>will have a deep impact on our codebases. Instead of explaining all the possibilities offered by this library, I will show you some ways of using it for specific use cases.</p><p>In this first post on coroutines, we are going to use them to scale out some intensive CPU operations on multiple cores. This post is inspired by <a href="http://doc.akka.io/docs/akka/2.0/intro/getting-started-first-scala.html">Akka introduction</a>.</p><h3>Computing Pi with Leibniz series</h3><p>Among various way of computing PI, we use <a href="https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80">Leibniz series</a> to calculate it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*ityTKc51rqeEkKTOvh349A.png" /></figure><p>It’s not the best implementation (some are converging faster) but it is quite simple (to code and understand) and highly parallelizable.</p><h3>Computing on the main thread</h3><p>Implementing the sum of elements is straightforward. We use a range type (start..end) and the extension function <em>sumByDouble</em> to avoid a loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gx-XjhhQMihRq1Z19rB45A.png" /></figure><p>Executing this method with elements from 0 and 1.000.000.000 computes PI with 9 significant digits.</p><p>On my laptop, the computation takes 4500 ms. But we can observe that only one core of CPU is used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*t2_107HJXX-tuKKO_0XXbA.png" /></figure><h3>Using Kotlin Coroutines to fan out computation</h3><p>We are going to reuse the previous function <em>sumLeibnizBetween</em> but making it asynchronous.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*njVJT6OxBkLQ9ayxXO6A8Q.png" /></figure><p>This code just wraps our previous function in a coroutine. Coroutines can be seen as lightweight threads. You can creates millions of them without problems. The <em>async(CommonPool)</em> gives the context of coroutines: they are created inside threads of java <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ForkJoinPool.html">ForkJoinPool</a>. This pool manages its worker threads taking account the number of processors.</p><p>Now we use this asynchronous function to dispatch our PI computation in parallel computations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mF-itQRLX8esbhahs5efow.png" /></figure><p>This function spans out the computation to <em>chunkCount</em> coroutines, each one computing <em>chunkSize</em> Leibniz elements.</p><p>Every call to <em>asyncSumLeibnizBetween</em> returns a <em>Deferred&lt;Double&gt;. </em>The last line of the function waits for every asynchronous returns and sum them up.</p><p>The <em>runBlocking</em> call is a bridge between regular blocking code and coroutines. It blocks the current thread until coroutines completion. It allows the code to come back from asynchronism to synchronism.</p><p>With <em>fanOutSumLeibniz</em> function the computation of 1.000.000.000 elements (10.000 chunks of 100.000 elements) spreads on almost all the cores (8 on this computer) and is 3.75 times faster (1200 ms).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*i03VDdVzQxxPFDOQZDL-sw.png" /></figure><p>All the code is <a href="https://github.com/gzoritchak/experiment">available on github</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ee3ad294674" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Genetic Algorithms with Kotlin]]></title>
            <link>https://medium.com/@gz_k/exploring-genetic-algorithm-with-kotlin-60dfd8d1509a?source=rss-36cd1b73c9ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/60dfd8d1509a</guid>
            <category><![CDATA[codingame]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[genetic-algorithm]]></category>
            <dc:creator><![CDATA[Gaetan Zoritchak]]></dc:creator>
            <pubDate>Tue, 07 Jun 2016 21:52:47 GMT</pubDate>
            <atom:updated>2016-06-23T11:50:38.871Z</atom:updated>
            <content:encoded><![CDATA[<p>This story is about chimps trying to land on Mars. Yes, really.</p><p>There are a lot and some of them can succeed. We use a genetic algorithm to select the best chimps of each generation until the selection is down to the hero who will land safely on Mars with the fullest fuel tank possible.</p><p><strong><em>Disclaimer:</em></strong> <em>This post is about my first experiments on genetic algorithms. I’m not an expert.</em></p><p><strong><em>Edit</em></strong>: <a href="https://github.com/gzoritchak/marslander">here is the complete project on github.</a></p><h3>Landing on Mars</h3><p>The algorithm answers <a href="https://www.codingame.com/games/puzzles">CodinGame’s first puzzle on landing on Mars</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*ACWz7GLvurmj5gSmJ-4QNw.png" /></figure><p>The Lander evolves in two dimensions. The chimp must control it using angle and thrust power commands. The gravity is -3,711 m/s² (see details on CodinGame’s website).</p><p>The challenge is to find the correct commands to have the lander hit the ground on the landing zone (horizontal) with a vertical speed lower than 40 m/s and an horizontal speed under 20 m/s.</p><h4>Genetic Algorithm principles</h4><p>Genetic Algorithms try to mimic the natural selection in order to resolve problems where solutions are hard to find.</p><p>The steps are :</p><ol><li>generate a population of random genomes,</li><li>convert theses genome into input parameters of our simulation,</li><li>play the simulation,</li><li>evaluate the results of each genome,</li><li>select the best genomes, recombine and mutate them to produce the next generation,</li><li>iterate until a solution is found.</li></ol><h3>Representing the model</h3><p>We must <strong>have a simulator representing precisely the model</strong>.</p><p>For that purpose, I split my code into a simplified cartesian system, small physics classes and the Lander.</p><p>This is the code of my <strong>simplified cartesian system</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd6188ca8cfb0df8bcd9f5d601ced51a/href">https://medium.com/media/dd6188ca8cfb0df8bcd9f5d601ced51a/href</a></iframe><p>The main idea of these classes is to simplify the manipulation of points, vector and lines.</p><p>Points and Vector will help us managing the position, the speed, the acceleration of the lander. The rotate function of Vector will be the only one containing trigonometry.</p><p>The line is here to represent Mars surface and check if the lander hits the ground.</p><p><a href="https://kotlinlang.org/docs/reference/operator-overloading.html">Kotlin operator overloading</a> is interesting to manipulate these concepts and simplify our domain. This will allow us to write code like:</p><pre><strong>val</strong> endPoint = startPoint + moveVector</pre><pre><strong>val</strong> composedVector = vector1 + vector2</pre><p>One more file for physics :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7e4e87f98d97f18df19cd6b2a6690c3/href">https://medium.com/media/d7e4e87f98d97f18df19cd6b2a6690c3/href</a></iframe><p>We now have all the basics to implement the Lander simulator:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f027029becbd456fe48babd7eb4f080/href">https://medium.com/media/8f027029becbd456fe48babd7eb4f080/href</a></iframe><p>The state class holds the Lander state at one moment : it’s position, angle, power, speed and fuel.</p><p>The ControlCmd holds the command that can be asked : an angle and a thrust power.</p><p>Given a lander at an initial state, we can simulate its complete trajectory after having applied a list of commands. The simulation should respect exactly the target domain constraints if we want our algorithm to be relevant. In our case, we check that applying a list of static commands ( 100 × (15°,power 1) for example) to an initial state results in having the Lander at the exact same state on <em>CodinGame</em> simulator.</p><p>Ok, we have our simulator. Now, let’s code the genetic algorithm.</p><h3>The Genetic Algorithm</h3><p>So here is the code of a generic Genetic Algorithm in kotlin:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8d6b225d9772675142155580a72c64a/href">https://medium.com/media/b8d6b225d9772675142155580a72c64a/href</a></iframe><p>The Gene class represents a single gene implemented by a random double. We provide a method to simplify its use as an Int.</p><p>A Genome is an array of Genes.</p><p>We have a utility class GenomeAndResult which keeps together a genome and the corresponding object created from it. This class is generic and can be reused for any domain.</p><p>The entry point of the algorithm is the <strong><em>findBestChimp</em></strong> function. This function takes two parameters that are also functions:</p><ol><li>A create function that builds a object from a genome.</li><li>A fitness function that evaluates an object according to the goal of the algorithm.</li></ol><p>The genetic algorithm creates a population from random genomes. The population is sorted with the fitness function. The selection process then randomly picks individuals, the best ones having more chances to procreate.</p><p>The creation of new individuals is done through a crossover combination of parent genomes. After the crossover, the genome is altered by mutations that help exploring new areas.</p><p>The last effort is now on implementing the <strong>function that creates a Lander from a genome</strong> and the <strong>fitness function</strong>. In fact it is the trickiest part. The performance of the genetic algorithm (it’s ability to rapidly converge to a solution) is defined by the quality of the creation and fitness functions.</p><p>Even if the lander crashed we should be able to compare the crashes to allow the algorithm to give more chances to the «best crashes» genomes.</p><p>Here is my code for the first CodinGame puzzle. The Lander has just a vertical trajectory and we don’t have to manage it’s angle.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b4e1391e10b20be9ac38958a5fb4ca4/href">https://medium.com/media/4b4e1391e10b20be9ac38958a5fb4ca4/href</a></iframe><p>Running the program we can see that the generations are rapidly converging to the best solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YfjX63SlGIeNESt0bifoJA.png" /></figure><p>Using the commands found by the algorithm shows a perfect landing.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FoS1m9kyZ6og%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DoS1m9kyZ6og&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FoS1m9kyZ6og%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/67d573e1921036699a7dcc90fcc2f5d9/href">https://medium.com/media/67d573e1921036699a7dcc90fcc2f5d9/href</a></iframe><p>All the code of the MarsLander 1 is available on <a href="https://github.com/gzoritchak/marslander">this github repository</a>.</p><p>Implementing the create and fitness functions for Mars Lander 2 requires 40 lines of code. Look them up for some nice touchdowns:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FrGdDuPQt2e8%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DrGdDuPQt2e8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FrGdDuPQt2e8%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba7b2b84e96183a2ae15225820a3d380/href">https://medium.com/media/ba7b2b84e96183a2ae15225820a3d380/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60dfd8d1509a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rest API plumbing with kotlin]]></title>
            <link>https://medium.com/@gz_k/rest-api-plumbing-with-kotlin-b161af052178?source=rss-36cd1b73c9ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/b161af052178</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Gaetan Zoritchak]]></dc:creator>
            <pubDate>Tue, 29 Mar 2016 09:19:40 GMT</pubDate>
            <atom:updated>2016-03-29T13:07:59.426Z</atom:updated>
            <content:encoded><![CDATA[<p>As a startup developper, I spend a lot of my time dealing with REST APIs. It can be internal APIs for our web applications or external APIs for integration with online services (email, documents, …). For both uses, Kotlin features help a lot. Lets see how.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hzb7OdfBZ9vYEosTTfLddg.png" /><figcaption>Internal and external REST calls</figcaption></figure><h4>Internal APIs</h4><p>Regardless the web framework we use (my preferred one is currently <em>Ember.js</em>) the client/server communication is commonly implemented via a REST API exchanging data in JSON.</p><p>We define our API by specifying URLs and the JSON Format. URLs’ definition is managed by the web framework. As for the JSON format, jackson is a good solution for serializing POJOs. The structure of the JSON object is defined by the POJOs property names. To be sure to have an API independent of our domain objects, we need to have specific classes for the client-server communication.</p><p>Jackson is a nice framework that converts java classes to JSON seamlessly. The main problem with java is the verbosity of those POJOs classes. Even basic javabeans with no logic and no method seems bloated.</p><p>In the other hand, Kotlin data classes are really concise and allow generally to define data objects in a single line.</p><p>For all JSON inputs and outputs, we can have the data classes contained in the same file/class as the Rest Controller.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*xdUrq3OnbITKiS4yXQhBnw.png" /><figcaption>Kotlin files that contains both the controller and the data classes</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XVMVPgmMzeBa4dBCa0TGAA.png" /><figcaption>Defining a PUT call with spring and kotlin</figcaption></figure><p>The Nullabillity type system of Kotlin gives more control and information on the input/output format. In the example above, the documentId can be null by specification.</p><p>In that call, the client expects an empty JSON object (?!). We can provide it by returning an instance of the <em>Empty</em> class.</p><p>For inputs, we need to use <a href="https://github.com/FasterXML/jackson-module-kotlin">jackson’s Kotlin</a> module. It manages the constructor calls to avoid creating unnecessary empty constructors.</p><p>In less than 20 lines of kotlin we have defined our REST call, the URL and the format.</p><h4>External APIs and the bounded context pattern</h4><p>Beyond the issue of connecting with an external API and the technical part of it (remote calls, authentication,…) as developers we have to manage the <a href="http://martinfowler.com/bliki/BoundedContext.html"><strong>Bounded Context pattern</strong></a>.</p><p>The external system has its own domain model, which makes sense in its context, but is certainly different from our model/context.</p><p>For example, the representation of Google Files in Google Drive is different from our file domain.</p><p>When retrieving objects from the external API we have to <strong>transform those objects in our own model</strong>. The transformation must deal with the values (retrieved or not) and the type of (generally different) properties .</p><p>Imagine the following naive class for my domain file:</p><pre><strong>class</strong> MyFile(<br>   <strong>val</strong> name:String, <br>   <strong>val</strong> creationDate: Instant, <br>   <strong>val</strong> modificationDate:Instant)</pre><p>In the <a href="https://developers.google.com/resources/api-libraries/documentation/drive/v2/java/latest/">Google API</a> dates are using <em>com.google.api.client.util.DateTime</em> type for creation and modification dates.</p><p>A first conversion function could be:</p><pre><strong>fun</strong> gFileToMyFile(gFile: File) = MyFile(<br>    gFile.title, <br>    Instant.ofEpochMilli(gFile.createdDate.value),<br>    Instant.ofEpochMilli(gFile.modifiedDate.value))</pre><p>It’s quite verbose and hard to read. We can improve the code by implementing a <strong>property extension</strong> on the google DateTime class:</p><pre><strong>val</strong> DateTime.instant: Instant <br>    get() = Instant.ofEpochMilli(value)</pre><p>The DateTime class now has a new property simplifying the previous code snippet:</p><pre><strong>fun</strong> gFileToMyFile(gFile: File) = MyFile(<br>    gFile.title, <br>    gFile.createdDate.<strong>instant</strong>, <br>    gFile.modifiedDate.<strong>instant</strong>)</pre><p>We can go further and <strong>replace this function</strong> with an <strong>extension function</strong> on the Google File class to call the transformation directly on the Google File instances.</p><pre><strong>fun</strong> File.toMyFile() = MyFile( <br>    title, <br>    createdDate.instant, <br>    modifiedDate.instant)</pre><p>Converting a single Google File is now as easy as:</p><pre><strong>val</strong> myFile = gFile.toMyFile()</pre><p>And the conversion of a list of files is done by mapping the original list using a function reference:</p><pre><strong>val</strong> myFiles = gFiles.map ( File::toMyFile )</pre><p>Implementing the 2 conversions (<em>Google DateTime =&gt; java Instant </em>and <em>Google File =&gt; MyFile) </em>with small <strong>extensions</strong> results in much more readable code.</p><p><strong>For both uses, managing internal and external APIs, Kotlin appears to be </strong><a href="https://blog.jetbrains.com/kotlin/2016/02/kotlin-1-0-released-pragmatic-language-for-jvm-and-android/"><strong>a great tool</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b161af052178" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>