<?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 Salomon Brys on Medium]]></title>
        <description><![CDATA[Stories by Salomon Brys on Medium]]></description>
        <link>https://medium.com/@timelzayus?source=rss-50a0a6ebc0db------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_kBvtrcAYaQw6mEd.jpg</url>
            <title>Stories by Salomon Brys on Medium</title>
            <link>https://medium.com/@timelzayus?source=rss-50a0a6ebc0db------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 20:05:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@timelzayus/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[Designing a Kotlin memory safe mode]]></title>
            <link>https://itnext.io/designing-a-kotlin-memory-safe-mode-c76c06317c3e?source=rss-50a0a6ebc0db------2</link>
            <guid isPermaLink="false">https://medium.com/p/c76c06317c3e</guid>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Salomon Brys]]></dc:creator>
            <pubDate>Mon, 26 Aug 2019 13:23:08 GMT</pubDate>
            <atom:updated>2019-08-27T10:05:05.766Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qGWYc4OCz7CxfWUy" /><figcaption>Photo by <a href="https://unsplash.com/@ryanmfranco?utm_source=medium&amp;utm_medium=referral">Ryan Franco</a></figcaption></figure><p>In my previous article, I shared my <a href="https://medium.com/@timelzayus/why-the-kotlin-native-memory-model-cannot-hold-ae1631d80cf6">frustration</a> about how the Kotlin/Native memory model is enforced at run-time, and proposed the beginning of language solution, having <strong>const</strong> in the type system.</p><p>Designing a language, even theoretically, is a very interesting challenge, so let’s put on our fake language designer hat, and see how we could offer a solution to the Kotlin/Native memory model.</p><p><em>Warning: this is a long article, describing a language feature that does not exist! I whish it did, though. This article describes the reasoning behind the proposal.</em></p><p>I am going to draw some comparisons with the Rust language, especially how rust handles <a href="https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html">ownership</a>, <a href="https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html">lifetime</a>, and <a href="https://doc.rust-lang.org/book/ch16-00-concurrency.html">concurrency</a>. You don’t have to read these links to understand this article, but if you want to dig deeper into these concepts, I highly recommend you do. Rust is an amazing language, with an amazing documentation.</p><p>When we want to extend an existing language, we first have to understand the framework of rules that governs this language.</p><p>Rust has a very strict framework of rules: if it is not explicitly allowed, then it is forbidden. Objects are immutable by default, unless specified mutable, you cannot pass pointers around unless specifically handling ownership, you cannot have multiple mutable references, etc.</p><p>Java on the other hand has a very “relaxed” framework of rules. If it is not explicitly forbidden, then it’s allowed. Everything is mutable, every class can be extended unless explicitly final, generic parameters are optional, etc.</p><p>Kotlin lies somewhere between: its designers keep saying that it is first and foremost pragmatic, which leads to some decisions that may look contradictory:</p><ul><li>Classes are final by default, but overrides are final only if explicit.</li><li>Objects are mutable but collection interfaces are first immutable, then mutable (MutableList extends List).</li><li>Nullability must be handled explicitly but all exceptions are implicit.</li></ul><p>So, I think that, when thinking of extending the Kotlin language, we must remember the following “pragmatic” framework of rules :</p><ul><li>Constraints must not get “in the way” of programmers. If the constraint is “worked around” more times than it is used, then it should not be enforced.</li><li>Code must be concise and explicit, meaning that the default behavior should be the more frequent one, but any change in behavior must be explicitly defined and readable.</li></ul><p>These 2 rules are the reason Kotlin enforces it most infamous rules: “everything is public by default”.</p><p>Finally, of course:</p><ul><li>New additions to the language must be backward compatible, not suddenly changing the semantic of existing Kotlin code.</li></ul><p>Let’s start.</p><p>First, from the famous Kotlin/Native memory model rule “a datum is either mutable or shared”, we can infer the exact opposite rule that describes the exact same concept: “a datum is either thread local or immutable”.</p><p>Kotlin/Native proposes a freeze API that renders an object (and all its subgraph) immutable. I’ve exposed in my previous article that I think this is a very bad idea to enforce immutability at run-time. So let’s introduce the <em>const</em> keyword in Kotlin.</p><p>C++ has an interesting approach to this: a type annotation. In Kotlin, it would look like this:</p><pre>fun description(foo: <strong>const</strong> Foo): String {}</pre><p>The <em>description</em> function states that it will not mutate the foo object, it will only read values from it. To enforce this, the compiler would only allow the function to access <em>const val geters</em> and <em>const functions</em>, something that in Kotlin would look like:</p><pre>class Foo {<br>    <strong>const</strong> val answer = 42<br>    <strong>const</strong> fun getName(): String = <em>TODO</em>()<br>}</pre><p>Here, the <em>getName</em> method is essentially pure, the compiler will ensure that it does not mutate the object (has no side effect).</p><p>This const type annotation is a very bad idea in Kotlin, for a lot of reasons:</p><ul><li>It would mean going over the entire standard library code-base to add <em>const</em> keyword to every pure functions such as <em>map</em>, <em>filter</em>, etc.</li><li>There would be <em>const</em> all over the place. The vast majority of functions and methods do not mutate data. Sure enough, the const keyword in C++ is everywhere, impairing readability.</li></ul><p>So why not make it the opposite? Say that everything is immutable unless explicitly defined mutable. Rust does that with the <em>mut</em> keyword. Unfortunately, while this is very appealing to programmers that love constrains (a group in which I proudly associate myself), we are not going to change the semantic of the entire existing Kotlin code-base. This would require everybody to go over all the Kotlin code that ever was created in order to add the <em>mut</em> keyword everywhere it is needed.</p><p>Not going to happen.</p><p>Here is something that could happen, though: a <em>const class annotation</em>. Something like this:</p><pre><strong>const</strong> class User(val firstName: String, val lastName: String) {<br>    fun fullName() = &quot;$firstName $lastName&quot;<br>}</pre><ul><li>At compile-time, the compiler ensures that <em>const</em> classes contain no <em>var</em> properties and only primitive or <em>const</em> values.</li><li>At run-time, in Kotlin/Native, all const classes reifications and their sub-trees are frozen by default.</li></ul><p>This eliminates the need for the freeze API. Objects are either const and frozen, or they’re not.<br>Some will argue that this removes the possibility to create and configure an object and later freeze it. I believe this is a huge code smell (you cannot know when the object has been frozen and it’s become forbidden to mutate it), and would redirect you to the <em>builder pattern</em>. Also: most garbage collectors have become experts at handling short-lived objects.</p><p>Yes, I’m aware this would still need some standard library changes: standard classes such as <em>String</em> would need to be annotated with <em>const</em>.</p><p>The next question is about polymorphism. Can we extend <em>const classes</em>? Are <em>const interfaces</em> allowed? If so, are all of their implementations required to be <em>const</em>?<br>These are very relevant questions, but irrelevant in the scope of this article. They do not need to be answered for this demonstration.<br>Also, I don’t know ;)</p><p>Side benefit: <em>const data classes</em> could have their <em>toString()</em> and <em>hashCode()</em> value generated at initialization and cached, which would greatly improve the performance of using data classes as Map keys. My last benchmark showed that caching hash code speeds up Map lookup by a factor of 3.</p><p>Let’s go back to our primal rule: “a datum is either thread local or immutable”. This means that the compiler should not allow non-const global values. This is the part where existing Kotlin code gets invalid.<br>Hopefully, Kotlin/Native is still in its early days, so I believe it would be acceptable to introduce a compiler <em>safe mode</em> that could or could not be enabled when using Kotlin/JVM or Kotlin/JS, but that would forcibly be enabled in any multi-platform project containing Kotlin/Native targets.</p><p>This “safe mode” would simply <strong>forbid mutable shared global state</strong> (but allow thread-local root variables):</p><pre>class Foo { <em>/*...*/ </em>}<br>const class Bar { <em>/*...*/ </em>}<br><br>val <em>foo </em>= Foo() <em>// </em><strong><em>Forbidden</em></strong><em>, Foo is not const<br></em>var <em>bar </em>= Bar() <em>// </em><strong><em>Forbidden</em></strong><em>, var are not allowed<br><br></em>val <em>global </em>= Bar() <em>// </em><strong><em>Allowed</em></strong><em><br></em><br>@ThreadLocal<br>var local = Foo() // <strong><em>Allowed</em></strong><em> (because thread-local)<br></em><br>fun main() { <em>TODO</em>() }</pre><blockquote>“Don’t communicate by sharing memory, share memory by communicating”.<br> — The Go language designers.</blockquote><p>This has become a moto for a lot of modern programming languages and programmers. At some points, threads need to communicate information between them, and can do so either by mutating shared data (which is bad, that’s the entire point) or by sending data from one to another.</p><p>Rust has the notion of <em>ownership</em> &amp; <em>lifetime</em>, which ensures that only one variable owns the data it contains and that the lifetime of the variable ends when it looses ownership of its value. This makes passing mutable objects between threads possible and safe.<br>These are notions that cannot make it in the Kotlin language, it’s way too late.</p><p>However, we have introduced the notion of const classes. Const classes objects are directly frozen, so they can be shared between threads. All we need is, for a function that handles thread message passing, a way to declare that it only accepts const value parameters.<br>Generics can help us here:</p><pre><strong>const</strong> class ConstChannel&lt;T : <strong>const</strong> Any&gt; { <em>/*...*/ </em>}<br><br>fun &lt;<strong>const</strong> T : Any&gt; newConstChannel(): ConstChannel&lt;T&gt; = <em>TODO</em>()</pre><p>The <em>ConstChannel</em> is a <em>const class</em>, so it can be safely shared between threads. It allows to send and receive data of type <em>T</em>, which must be <em>const</em> themselves.<br>How can <em>ConstChannel</em> be a <em>const class</em>, and yet handle inter-thread message passing internals (which definitely needs mutability)? Keep reading !</p><p>In Kotlin, lambda functions can capture outer scope values and variables. In essence, they are really closures and should not be called lambdas.</p><p>What if we are using the <em>Executor Pattern</em> (or the Kotlin/Native worker API) and want to schedule a lambda to run on an executor. There is a high probability chance that the code will be executed on another thread, which means that this lambda must not be able to capture non-const values.</p><p>Here is how you would declare the executor class:</p><pre><strong>const</strong> class ConstExecutor {<br>    fun schedule(block: <strong>const</strong> () -&gt; Unit) = TODO()<br>}</pre><p>Block is a <em>const lambda</em>, meaning that it can only capture const values. The following example illustrate its usage:</p><pre><strong>const</strong> data class GameState(val level: Int)<br><br>val <em>executor </em>= ConstExecutor()<br><br>fun save(level: Int) {<br>    val state = GameState(level)<br>    <em>executor</em>.schedule <strong>{ </strong>writeToFile(state) <strong>}<br></strong>}</pre><p>Because state is of type <em>GameState</em>, and because <em>GameState</em> is a <em>const class</em>, the lambda can capture it.<br>By contrast this code would <strong>not</strong> compile:</p><pre>fun save(level: Int) {<br>    var saveLevel = level<br>    if (level &gt; 10)<br>        saveLevel -= 1 <em>// Games become hard and frustrating!<br>    executor</em>.schedule <strong>{<br>        </strong>writeToFile(GameState(saveLevel))<br>        <em>//                    ^^^^^^^^^<br>        // Cannot capture a mutable value!<br>    </em><strong>}<br></strong>}</pre><p>How can <em>ConstExecutor</em> be a <em>const class</em>, and yet handle inter-thread scheduling internals (which definitely needs mutability)? Keep reading !</p><p>We need a way to screw up. Or more specifically, we need a way to go around these limitations. Something like the !! operator where we can say to the compiler “you can’t be the guarantee of this value’s nullability but I can, trust me ; I accept the possibility of a run-time crash if I’m mistaken”.</p><p>Kotlin/Native already does that with the <em>Atomic*</em> classes, which are classes that allows mutation while frozen.</p><p>We have defined the possibility of a <em>const lambda</em>, which can only capture const values, but there’s nothing preventing such lambdas from returning non-const value. Consider the following definition:</p><pre><strong>const</strong> class Attachable&lt;T&gt;(creator: <strong>const</strong> () -&gt; T) {<br>    fun &lt;R : <strong>const</strong> Any?&gt; attach(block: <strong>const</strong> (T) -&gt; R): R<br>}</pre><p>Let’s break this down.</p><ul><li><em>Attachable</em> is a <em>const class</em>, so it can be shared between threads.</li><li>The <em>creator</em> constructor parameter is a <em>const lambda,</em> which ensures that it returns either a captured const value (safe to share) or a new mutable data with no other references (since the lambda cannot capture mutable data) which can safely be detached / reattached between threads.</li><li>The attach function executes the <em>block const lambda</em> attaching the mutable data to the current thread for the duration of the lambda’s execution.<br>Because it is a <em>const lambda</em> with a <em>const return</em>, it cannot escape or “leak” references outside of the lambda.</li><li>If multiple threads attach at the same time, it will <strong>crash at run-time in Kotlin/native but not in Kotlin/JVM</strong> (but race conditions may occur).</li></ul><p>So, why oh why? Why get a headache designing a beautiful safe system only to provide the baseball bat to destroy it all? We wanted to ensure no crash at run-time, we wanted to ensure similar semantic whatever the target, and we destroyed these two dreams in 3 lines of code.</p><p>We’ve put everything we wanted to avoid in a single class. In essence, we’ve <strong>confined unsafety</strong> into <em>Attachable</em>. This leads to the following point: <em>do not use Attachable if you’re an application developer</em>. The <em>Attachable</em> class exists only for library developers to provide application developers higher level &amp; safer tools such as <em>ConstChannel</em> &amp; <em>ConstExecutor</em>.</p><p>Rust does exactly this with the <a href="https://doc.rust-lang.org/book/ch16-04-extensible-concurrency-sync-and-send.html">Sync &amp; Send traits</a>. Use it only if you’re designing a higher level tool that properly handles safety. Remember that when using it, you’re in unsafe territories, here be dragons.</p><p>With this <em>Attachable</em> class, it becomes trivial to create a multi-platform mutex that uses <em>ReentrantLock</em> in Kotlin/JVM, and <em>pthread_mutex</em> in Kotlin/Native, which leads to the possibility of deadlocks.</p><p>Mutexes are not a bad thing, they are often way faster than inter-thread message passing, and are needed for low-level, high performance stuff that, for example, Kotlin/Native embedded developers might need to write.<br>Most deadlocks are easy to debug. Just pause the app in your debugger and see which mutexes are being waited by which threads.<br>Race conditions, on the other hand are very hard to find and correctly debug, because you cannot pause when they happen. You cannot reliably detect them.<br>This is why I am perfectly OK with a framework of programming rules that allows for deadlock, but makes race conditions impossible.</p><p>I sincerely hope the Kotlin language &amp; the Kotlin/Native compiler can evolve to a safer, better framework of rules that:</p><ul><li>Encourages safe patterns &amp; practices.</li><li>Enforces constraints at compile time.</li><li>Allows unsafe code if needed.</li></ul><p>All this <em>const</em> thing won’t make it into the Kotlin language (I work neither at Jetbrains nor on Kotlin compilers), but I do hope this can be an example of a way to “fix” the current situation.<br>Both the Kotlin Multiplatform &amp; the Kotlin/Native stories can be improved, and we, as a community, may be the spark that creates the discussion, that creates the movement, that leads to the solution.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c76c06317c3e" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/designing-a-kotlin-memory-safe-mode-c76c06317c3e">Designing a Kotlin memory safe mode</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why the Kotlin/Native memory model cannot hold.]]></title>
            <link>https://itnext.io/why-the-kotlin-native-memory-model-cannot-hold-ae1631d80cf6?source=rss-50a0a6ebc0db------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae1631d80cf6</guid>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-native]]></category>
            <dc:creator><![CDATA[Salomon Brys]]></dc:creator>
            <pubDate>Mon, 19 Aug 2019 09:24:56 GMT</pubDate>
            <atom:updated>2021-09-22T11:29:02.434Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9D1Mwf982eJTzhUq" /><figcaption>Frozen is beautiful. (Photo by <a href="https://unsplash.com/@giacbrd?utm_source=medium&amp;utm_medium=referral">Giacomo Berardi</a>)</figcaption></figure><p><strong><em>EDIT: The memory model described in this article DID NOT HOLD. Jetbrains announced a much needed change in a </em></strong><a href="https://blog.jetbrains.com/kotlin/2020/07/kotlin-native-memory-management-roadmap/"><strong><em>July 2020 post</em></strong></a><strong><em>, which has been updated in a </em></strong><a href="https://blog.jetbrains.com/kotlin/2021/05/kotlin-native-memory-management-update/"><strong><em>May 2021 post</em></strong></a><strong><em>.<br>This article is still relevant as the new memory manager hasn&#39;t made stable or default yet.<br>However, be aware that everything described in this article WILL CHANGE in the future, and that Jetbrains is actively working on alleviating the described pain.</em></strong></p><p>So you’ve heard about Kotlin Multiplatform, that it’s different from what you’re usually seeing attached to the silver bullet that is Multiplatform:</p><ul><li>It actually compiles to “native” binaries. Meaning JVM bytecode for Android or LLVM / binary bits for iOS.</li><li>It proposes an entire code architecture dedicated to Multiplatform that allows platform specific implementations.</li><li>It has amazing interoperability stories, whether with or from Swift, JS, C &amp; of course Java.</li><li>It is developed and supported by the company that actually designed the language, so it is not “added” on top of the language, but baked in from its inception.</li></ul><p>So maybe this time, it will be different. Maybe it’ll work. Maybe there is a silver bullet.<br>With joy at heart, you start porting your JVM dependent Kotlin code to a Multiplatform architecture, it compiles !</p><p>You run it…</p><pre>Uncaught Kotlin exception: kotlin.native.concurrent.InvalidMutabilityException: mutation attempt of frozen com.Whatever@1aec038</pre><p>This happens because, yeah, Kotlin/Native runtime actually forces a batch of very important threading related code sanity rules, the first being:</p><blockquote>A datum is EITHER mutable OR shared.</blockquote><p>If you need to share an object, you can freeze it, because:</p><blockquote>A frozen datum cannot be mutated.</blockquote><p>Also:</p><blockquote>Freezing an object freezes everything it references.<br>A frozen object cannot be unfrozen.</blockquote><p>So, what about “static” data, such as top level variables or objects?<br>Well:</p><blockquote>Top-level objects are frozen by default.</blockquote><p>This isn’t a story about how to get passed those limitations or how to properly work your code to work on Kotlin Multiplatform.<br>This is a story about the limitations themselves.</p><p>First of all, we need to understand the reason behind these limitations. They are philosophical and practical.</p><p>Philosophically, this is a paradigm shift. Without shareable mutable data, there is no mutex needed, which means no race condition as well as fixed performance. This model encourages us to think our code in a different way than we are used to: rather than sharing the resources between threads, we name a thread that is responsible for the resource and send actions to it. Only one thread accesses the resource, all other threads ask the owner thread to perform actions on it on their behalf. This model is called “Actor Based Programming” and is made <a href="https://kotlinlang.org/docs/reference/coroutines/shared-mutable-state-and-concurrency.html#actors">really easy</a> by the KotlinX Coroutines library (which, funny enough, do not support multi-threading on Kotlin/Native precisely because of these restrictions. They are, however, <a href="https://github.com/Kotlin/kotlinx.coroutines/issues/462">working on it</a>).</p><p>Practically, enforcing this means that the runtime garbage collector is a lot more easy to write, optimizable and predictable.</p><p>I really like these constraints. I happen to think that the more constraints a programming language forces upon us, the more protected we are against releasing buggy apps.</p><p>So, what are the issues with these constrains?<br>Sadly, many. While the constrains themselves are sensible and very interesting, their implementation in the Kotlin/Native compiler &amp; runtime is problematic. Here’s why:</p><p><strong>1: These limitations are Kotlin/Native only</strong></p><p>Kotlin/Native has value only as part of the Multiplatform experience. Sad but true. There’s no iOS programmer that makes an iOS only app in Kotlin rather than in Swift. Nor there is a high performance server programmer that will favor Kotlin/Native over C++ or Rust. Same goes for high performance desktop apps.<br>The only domain where Kotlin/Native might get some traction on its own is embedded. And that’s far from done.</p><p>Because those limitations are Kotlin/Native only, they are pushing programmers away from the Kotlin Multiplatform experience. Most of them are discouraged by the idea of having to rethink their entire architecture when they were trying to port an existing working code.</p><p>Also, because the corresponding API only exists in Kotlin/Native, this makes <a href="https://github.com/Kotlin/kotlinx.coroutines/issues/462#issuecomment-450035178">almost impossible</a> to write some libraries with common code &amp; common semantics.</p><p><strong>2: These limitations are pure. We are practical.</strong></p><p>The first time you start thinking in Actor Based Programming, your mind blows. You feel enlightened, intelligent. Breaking your code into actors means compartmentalizing resources and responsibilities. Each actor is atomic in its function, and every actor can communicate to other actors for requests that are outside of their atomic function. This is a very interesting, safe, and great way of coding… Until you start benchmarking.</p><p>Please understand that I am far from those who think that #PerfMatters everywhere, every time. I am more of an “efficiency over performance” guy. However, there are times where performance does really matter. Everything depends on the context, and we cannot rule out the necessity of performance in critical paths.</p><p>Have a look at <a href="https://gist.github.com/SalomonBrys/688b2ccc10e3a7cea47966bf57d1cf89">this benchmark</a>. Here’s what it prints:</p><pre>With Mutex:<br>Completed 1000000 actions in 661 ms<br>Counter = 1000000<br>With Semaphore:<br>Completed 1000000 actions in 413 ms<br>Counter = 1000000<br>With Lock:<br>Completed 1000000 actions in 81 ms<br>Counter = 1000000<br>With Actor:<br>Completed 1000000 actions in 576 ms<br>Counter = 1000000</pre><p>System Locks are 7 times faster than actors. This <em>may</em> be a big deal.<br>If the shared resource is not accessed by a critical path, then the performance of actors is absolutely fine. If it is, though, that’s problematic.<br>That’s because there’s only <em>one</em> actor that’s confined to <em>one</em> thread. The beauty of Actor Based Programming is also its weakness: every time you need to access the resource, there’s a message passing between threads.</p><p>Actors are great most of the time, but not every time.</p><p>Oh. This benchmark does not even show the benefit of using a ReadWriteLock as it is very context dependent, but with few writes and lots of reads, using such a lock can further increase the performance factor over actors.</p><p><strong>3: These limitations are enforced at runtime</strong></p><p>A code that compiles and works fine in JVM or JS will <strong>crash at runtime</strong> in Native.<br>All it takes is 5 lines of code:</p><pre>object Foo { var bar = 21 }<br>fun main() {<br>    Foo.bar = 42 // Crash happens here!<br>    <em>println</em>(Foo.bar)<br>}</pre><p>Remember? This is the work of “<em>top-level objects are frozen by default</em>” and “<em>a frozen datum cannot be mutated</em>”.</p><p>Because these limitations are enforced at runtime, neither the compiler nor the IDE will warn you that you are doing something <em>verboten</em>. It will compile, run fine in JVM &amp; JS, and crash in Native.<br>In fact, there is no way the compiler &amp; the IDE can warn you, because immutability is not part of the type system.</p><p>The impact of points 1 &amp; 2 are similar: this discourages developers. Regarding the point of view, this can be a good or a bad thing. Someone might say “If you don’t like doing things rights, go away from my language”. Yes, forcing developers enforce good practices is a very good thing. We all love that nullability is embedded into the Kotlin type system, even if we have to write additional nullability checks.<br>Forcing developers into a paradigm shift may be a good thing, but I fear JetBrains has underestimated the cost of such a shift. I fear that by forcing developers into their “better” way, they are actually pushing them away. It’s a hunch, I have no data backing it. However, as a professional certified Kotlin trainer, I have seen the adoption of Kotlin/Native being delayed precisely because of this.</p><p>However, what bugs me the most is by far point 3. For the life of me, I cannot understand how JetBrains thought that it would be OK to have such an easy code compile and crash at runtime.<br>One of the main reasons Kotlin is so popular is <em>precisely</em> because a lot of crashes are detected at compile time, preventing the app from compiling and therefore deploying. This is why people love nullability, smart casts, (very) strong typing, etc.<br>Having immutability enforced at runtime feels like a huge mistake. It feels like <em>letting the wolf into the sheepfold</em> (french expression). Suddenly, code that compiles and work in any other platform crashes without so much of a warning in Kotlin/Native. Suddenly, it feels like the language is working against us, rather than with us. It feels like Kotlin has betrayed us.</p><p>There are two ways the situation can improve. Either fix the language or fix the runtime.</p><p>How could we fix the language? One approach would be to add <strong>const classes</strong> to the language, which would be described as “a class with only immutable data: either primitives or const objects”. One benefit of this approach is to allow for <a href="https://github.com/Kotlin/KEEP/pull/51">hashcode optimization</a>. Then there would be no need for the freeze() API: const classes are the definition of frozen. Furthermore, “const” is already a language keyword.<br>Another way would be to implement <a href="https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html">ownership</a> &amp; <a href="https://doc.rust-lang.org/book/ch16-00-concurrency.html">concurrency primitives</a> like Rust does. I’d love this, but I fear Kotlin has moved away from these principles too much already and that it’s too late (also, ownership in Rust is highly coupled with memory collection).</p><p>Sadly, fixing the language is by far a more complicated &amp; daunting approach, so it looks like JetBrains is taking <a href="https://github.com/JetBrains/kotlin-native/pull/3129">the easier path</a>. Is it a good thing?<br>I should say that there’s no way to be sure that this new “relaxed mode” will actually ship. It may be just a test.<br>Fixing the runtime does lower the entry bar, as every programmer can continue to code the way they used to, but I can’t stop the feeling that we, as a language community, may be loosing the dream of “correct concurrency”. Maybe we haven’t tried hard enough?</p><p>Here comes the conclusion: in its current form, its memory model is hurting Kotlin/Native. It makes it very difficult to write multiplatform code that has the same semantic regardless of the platform, it drives developers away because of it, and it makes it feel like the language is working against us by crashing at runtime enforcing arbitrary rules that aren’t shown by tooling.</p><p>It cannot hold.<br>I really hope it won’t.</p><p>This doesn’t mean that the paradigm itself is wrong. Just the implementation. There are loads of ways to implement this in a correct, less frustrating way, and I sincerely hope the Kotlin language designers will take this road.<br>And if it doesn’t, well, compiler plugins may be a way for us to try new things!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae1631d80cf6" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/why-the-kotlin-native-memory-model-cannot-hold-ae1631d80cf6">Why the Kotlin/Native memory model cannot hold.</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>