<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://www.albertlatacz.com/feed.xml" rel="self" type="application/atom+xml" /><link href="https://www.albertlatacz.com/" rel="alternate" type="text/html" /><updated>2025-10-27T11:02:56+00:00</updated><id>https://www.albertlatacz.com/feed.xml</id><title type="html">Making software happen…</title><subtitle>Albert Latacz - Technical Lead • Security And Testability Craftsman • Software Development Mentor • Open Source Contributor • Founder</subtitle><author><name>Albert Latacz</name></author><entry><title type="html">Kotlin Fundamentals : Sealed Classes</title><link href="https://www.albertlatacz.com/blog/kotlin-fundamentals-sealed-classes/" rel="alternate" type="text/html" title="Kotlin Fundamentals : Sealed Classes" /><published>2024-07-12T08:25:00+00:00</published><updated>2024-07-12T08:25:00+00:00</updated><id>https://www.albertlatacz.com/blog/kotlin-fundamentals-sealed-classes</id><content type="html" xml:base="https://www.albertlatacz.com/blog/kotlin-fundamentals-sealed-classes/"><![CDATA[<p>One of the stand-out fundamental features in Kotlin are sealed classes. Sealed classes allow developers to define a 
closed set of subclasses, making it easier to manage and maintain complex codebases. This article delves into the 
fundamentals of sealed classes, exploring their advantages, implementation, common use cases, and best practices.</p>

<p>By the end, you’ll have a solid understanding of how to leverage sealed classes to write more robust and maintainable code.</p>

<h1 id="what-is-a-sealed-class">What Is A Sealed Class?</h1>

<p>Sealed class in Kotlin allows developers to create a restricted class hierarchy. Unlike regular classes, sealed classes can only 
be subclassed within the same package where they are declared. This ensures that all possible subclasses are known at 
compile-time, providing better type safety and exhaustiveness checks when dealing with class hierarchies.</p>

<p>A sealed class is declared using the <code class="language-plaintext highlighter-rouge">sealed</code> keyword, and its subclasses are typically defined as either classes or 
objects within the same file. This setup helps in representing a fixed set of possible types, similar to enums but with 
the flexibility of classes. For example, sealed classes are particularly useful in scenarios where you have a 
limited set of operations that can be performed, and you want to enforce this restriction throughout your codebase.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
</pre></td><td class="rouge-code"><pre><span class="k">sealed</span> <span class="kd">class</span> <span class="nc">Shape</span>
<span class="kd">class</span> <span class="nc">Circle</span><span class="p">(</span><span class="kd">val</span> <span class="py">radius</span><span class="p">:</span> <span class="nc">Double</span><span class="p">)</span> <span class="p">:</span> <span class="nc">Shape</span><span class="p">()</span>
<span class="kd">class</span> <span class="nc">Rectangle</span><span class="p">(</span><span class="kd">val</span> <span class="py">width</span><span class="p">:</span> <span class="nc">Double</span><span class="p">,</span> <span class="kd">val</span> <span class="py">height</span><span class="p">:</span> <span class="nc">Double</span><span class="p">)</span> <span class="p">:</span> <span class="nc">Shape</span><span class="p">()</span>
<span class="kd">object</span> <span class="nc">Unknown</span> <span class="p">:</span> <span class="nc">Shape</span><span class="p">()</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>In this example, <code class="language-plaintext highlighter-rouge">Shape</code> is a sealed class with three possible types: <code class="language-plaintext highlighter-rouge">Circle</code>, <code class="language-plaintext highlighter-rouge">Rectangle</code>, and a singleton object <code class="language-plaintext highlighter-rouge">Unknown</code>. 
The compiler knows all possible subclasses of <code class="language-plaintext highlighter-rouge">Shape</code>, enabling it to perform exhaustive checks e.g. when you use a <code class="language-plaintext highlighter-rouge">when</code> 
expression to handle different shapes, you can be sure all cases are covered, or the compiler will warn you if you miss any.</p>

<p>Sealed classes thus provide a way to model complex data structures while maintaining type safety and ensuring your code 
is robust and less prone to errors. They strike a balance between the simplicity of enums and the flexibility of class 
inheritance, making them a useful tool in every Kotlin developer’s toolbox.</p>

<h1 id="why-not-just-enums">Why Not Just Enums?</h1>
<p>Enums are suitable for representing a fixed set of constants, but they lack the flexibility of sealed classes.
Enums cannot have properties or methods specific to each constant, whereas sealed classes allow each subclass to have
its own properties and methods. This makes sealed classes more versatile for modeling complex data structures.
However, enums are simpler and more concise when you only need to represent a small, fixed set of values
without additional behavior.</p>

<h1 id="advantages-of-using-sealed-classes">Advantages Of Using Sealed Classes</h1>

<p>Sealed classes offer several advantages that make them an attractive choice for developers. Firstly, they provide exhaustive <code class="language-plaintext highlighter-rouge">when</code> expressions. 
Because all subclasses of a sealed class are known at compile-time, the compiler can enforce that all possible cases are handled. 
This reduces the likelihood of runtime errors and makes the code more robust.</p>

<p>Another advantage is improved readability and maintainability. Sealed classes allow you to define a clear and constrained 
hierarchy, making it easier to understand the possible types and their relationships. This can significantly reduce the 
cognitive load on developers, as they do not need to consider unknown subclasses scattered across the codebase. 
All possible subclasses are defined in one package, providing a clear and concise overview.</p>

<p>Sealed classes also enhance type safety. By restricting the set of subclasses, sealed classes ensure that you can 
only work with a known set of types. This reduces the risk of type-related bugs and makes the code easier to reason about.
For instance, if you add a new subclass, the compiler will alert you to update all relevant expressions, 
ensuring that your code remains consistent and correct.</p>

<p>Furthermore, sealed classes can encapsulate state and behavior more effectively than enums. While enums are useful for 
representing a fixed set of constants, sealed classes offer more flexibility by allowing each subclass to have its own 
properties and methods. This makes sealed classes ideal for modeling complex data structures and domain-specific logic.</p>

<h1 id="examples">Examples</h1>

<h3 id="error-handling">Error Handling</h3>

<p>Imagine you’re building a data-fetching function that could either succeed or fail. With sealed classes, you can create 
a clean, type-safe representation of these outcomes.</p>

<p>We’ll define a <code class="language-plaintext highlighter-rouge">Result</code> sealed class with two subclasses: <code class="language-plaintext highlighter-rouge">Success</code> and <code class="language-plaintext highlighter-rouge">Error</code>. The <code class="language-plaintext highlighter-rouge">Success</code> class will hold the 
successfully fetched data, while the <code class="language-plaintext highlighter-rouge">Error</code> class will contain information about what went wrong.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
</pre></td><td class="rouge-code"><pre><span class="k">sealed</span> <span class="kd">class</span> <span class="nc">Result</span><span class="p">&lt;</span><span class="k">out</span> <span class="nc">T</span><span class="p">&gt;</span> <span class="p">{</span>
    <span class="kd">data class</span> <span class="nc">Success</span><span class="p">&lt;</span><span class="k">out</span> <span class="nc">T</span><span class="p">&gt;(</span><span class="kd">val</span> <span class="py">data</span><span class="p">:</span> <span class="nc">T</span><span class="p">)</span> <span class="p">:</span> <span class="nc">Result</span><span class="p">&lt;</span><span class="nc">T</span><span class="p">&gt;()</span>
    <span class="kd">data class</span> <span class="nc">Error</span><span class="p">(</span><span class="kd">val</span> <span class="py">reason</span><span class="p">:</span> <span class="nc">String</span><span class="p">)</span> <span class="p">:</span> <span class="nc">Result</span><span class="p">&lt;</span><span class="nc">Nothing</span><span class="p">&gt;()</span>
<span class="p">}</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>This setup allows you to return a <code class="language-plaintext highlighter-rouge">Result</code> object from your functions, ensuring that calling code must handle 
both success and failure cases. It’s a compile-time guarantee that you won’t forget to deal with errors.</p>

<p>Using this <code class="language-plaintext highlighter-rouge">Result</code> type, you can write functions that clearly express their potential outcomes:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
</pre></td><td class="rouge-code"><pre><span class="k">fun</span> <span class="nf">fetchUser</span><span class="p">(</span><span class="n">id</span><span class="p">:</span> <span class="nc">String</span><span class="p">)</span> <span class="p">=</span> <span class="k">try</span> <span class="p">{</span>
    <span class="nc">Success</span><span class="p">(</span><span class="nf">getUser</span><span class="p">(</span><span class="n">id</span><span class="p">))</span>
<span class="p">}</span> <span class="k">catch</span> <span class="p">(</span><span class="n">e</span><span class="p">:</span> <span class="nc">Exception</span><span class="p">)</span> <span class="p">{</span>
    <span class="nc">Error</span><span class="p">(</span><span class="s">"Failed to fetch user: ${e.message}"</span><span class="p">)</span>
<span class="p">}</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>When using this function, you’re forced to handle both cases, leading to more robust code:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
</pre></td><td class="rouge-code"><pre><span class="k">when</span> <span class="p">(</span><span class="kd">val</span> <span class="py">result</span> <span class="p">=</span> <span class="nf">fetchUser</span><span class="p">(</span><span class="s">"123"</span><span class="p">))</span> <span class="p">{</span>
    <span class="k">is</span> <span class="nc">Success</span> <span class="p">-&gt;</span> <span class="nf">displayUser</span><span class="p">(</span><span class="n">result</span><span class="p">.</span><span class="n">data</span><span class="p">)</span>
    <span class="k">is</span> <span class="nc">Error</span> <span class="p">-&gt;</span> <span class="nf">showErrorMessage</span><span class="p">(</span><span class="n">result</span><span class="p">.</span><span class="n">reason</span><span class="p">)</span>
<span class="p">}</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>This pattern promotes cleaner, more maintainable code by making error handling explicit and encouraging developers to 
consider all possible outcomes. It’s a prime example of how Kotlin’s sealed classes can improve code quality and 
reduce bugs related to unexpected states or unhandled errors.</p>

<h3 id="modelling-system-commands">Modelling System Commands</h3>

<p>Sealed classes in Kotlin prove invaluable when modeling system commands, especially in scenarios where you need to 
represent a finite set of operations. Let’s explore how we can use sealed classes to create a robust command structure 
for a hypothetical file system manager.</p>

<p>Imagine you’re building a file system utility that needs to handle various operations like creating directories, 
deleting files, and moving items. Each of these commands might require different parameters and behave uniquely. 
Sealed classes offer a neat solution to model these diverse yet related commands.</p>

<p>Here’s how you might structure your system commands:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
6
</pre></td><td class="rouge-code"><pre><span class="k">sealed</span> <span class="kd">class</span> <span class="nc">FileSystemCommand</span> <span class="p">{</span>
    <span class="kd">data class</span> <span class="nc">CreateDirectory</span><span class="p">(</span><span class="kd">val</span> <span class="py">path</span><span class="p">:</span> <span class="nc">String</span><span class="p">)</span> <span class="p">:</span> <span class="nc">FileSystemCommand</span><span class="p">()</span>
    <span class="kd">data class</span> <span class="nc">DeleteFile</span><span class="p">(</span><span class="kd">val</span> <span class="py">path</span><span class="p">:</span> <span class="nc">String</span><span class="p">)</span> <span class="p">:</span> <span class="nc">FileSystemCommand</span><span class="p">()</span>
    <span class="kd">data class</span> <span class="nc">MoveItem</span><span class="p">(</span><span class="kd">val</span> <span class="py">sourcePath</span><span class="p">:</span> <span class="nc">String</span><span class="p">,</span> <span class="kd">val</span> <span class="py">destinationPath</span><span class="p">:</span> <span class="nc">String</span><span class="p">)</span> <span class="p">:</span> <span class="nc">FileSystemCommand</span><span class="p">()</span>
    <span class="kd">object</span> <span class="nc">ListContents</span> <span class="p">:</span> <span class="nc">FileSystemCommand</span><span class="p">()</span>
<span class="p">}</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>This structure provides several benefits. First, it ensures type safety – you can only create commands that are 
explicitly defined. Second, it allows you to use Kotlin’s when expression to handle each command type exhaustively, 
preventing oversight of any command type.</p>

<p>You can then create a command processor that handles these commands:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
6
</pre></td><td class="rouge-code"><pre><span class="k">fun</span> <span class="nf">processCommand</span><span class="p">(</span><span class="n">command</span><span class="p">:</span> <span class="nc">FileSystemCommand</span><span class="p">)</span> <span class="p">=</span> <span class="k">when</span> <span class="p">(</span><span class="n">command</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">is</span> <span class="nc">CreateDirectory</span> <span class="p">-&gt;</span> <span class="nf">createDir</span><span class="p">(</span><span class="n">command</span><span class="p">.</span><span class="n">path</span><span class="p">)</span>
    <span class="k">is</span> <span class="nc">DeleteFile</span> <span class="p">-&gt;</span> <span class="nf">deleteFile</span><span class="p">(</span><span class="n">command</span><span class="p">.</span><span class="n">path</span><span class="p">)</span>
    <span class="k">is</span> <span class="nc">MoveItem</span> <span class="p">-&gt;</span> <span class="nf">moveItem</span><span class="p">(</span><span class="n">command</span><span class="p">.</span><span class="n">sourcePath</span><span class="p">,</span> <span class="n">command</span><span class="p">.</span><span class="n">destinationPath</span><span class="p">)</span>
    <span class="k">is</span> <span class="nc">ListContents</span> <span class="p">-&gt;</span> <span class="nf">listContents</span><span class="p">()</span>
<span class="p">}</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>This approach offers clear advantages in terms of code organization and maintainability. As your system grows, you can 
easily add new command types without modifying existing code, adhering to the open-closed principle. It also provides 
a clear interface for other parts of your application to interact with the file system operations, enhancing modularity and testability.</p>

<h1 id="best-practices">Best Practices</h1>

<p>To get the most out of sealed classes in Kotlin, it’s essential to follow best practices that ensure your code is clean, maintainable, and efficient.</p>

<h3 id="define-in-the-same-file">Define In The Same File</h3>

<p>This enforces the restriction that sealed classes provide and ensures the compiler can perform exhaustive checks. 
Although you can define sealed classes in a package defining them in one file improves readability by keeping the related types together.</p>

<h3 id="use-for-representing-fixed-hierarchies">Use For Representing Fixed Hierarchies</h3>
<p>Sealed classes are ideal for scenarios where you have a well-defined set of possible types. Use them to model state 
machines, command patterns, or any situation where the set of types is fixed and known at compile-time.</p>

<h3 id="leverage-exhaustive-when">Leverage Exhaustive <code class="language-plaintext highlighter-rouge">when</code></h3>
<p>Take advantage of the compiler’s ability to check for exhaustiveness in <code class="language-plaintext highlighter-rouge">when</code> expressions.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
</pre></td><td class="rouge-code"><pre><span class="k">fun</span> <span class="nf">describeShape</span><span class="p">(</span><span class="n">shape</span><span class="p">:</span> <span class="nc">Shape</span><span class="p">)</span> <span class="p">=</span> <span class="k">when</span> <span class="p">(</span><span class="n">shape</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">is</span> <span class="nc">Circle</span> <span class="p">-&gt;</span> <span class="s">"Circle with radius ${shape.radius}"</span>
    <span class="k">is</span> <span class="nc">Rectangle</span> <span class="p">-&gt;</span> <span class="s">"Rectangle with width ${shape.width} and height ${shape.height}"</span>
    <span class="nc">Unknown</span> <span class="p">-&gt;</span> <span class="s">"Unknown Shape"</span>
<span class="p">}</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>Ensure that all possible subclasses are handled, either by explicitly listing them or using the <code class="language-plaintext highlighter-rouge">else</code> branch for completeness. 
This reduces the risk of runtime errors and makes your code more robust.</p>

<h3 id="avoid-overuse">Avoid Overuse</h3>
<p>While sealed classes are powerful, they are not always the best solution. Avoid overusing them in situations where 
other class types, such as enums, interfaces, or abstract classes, might be more appropriate. Use sealed classes 
when the benefits of type safety and controlled hierarchies are most relevant.</p>

<h1 id="conclusion">Conclusion</h1>

<p>Sealed classes are a powerful feature in Kotlin that provide a way to represent restricted class hierarchies with 
enhanced type safety and maintainability. By allowing only a fixed set of subclasses, sealed classes enable 
exhaustive expressions and improve code readability. They are particularly useful for modeling state machines, 
algebraic data types, and complex states. By understanding and implementing sealed classes effectively, you can 
leverage their advantages to create robust and maintainable Kotlin applications. Embrace sealed classes in your 
Kotlin projects to ensure a more structured and error-resistant codebase.</p>]]></content><author><name>Albert Latacz</name></author><category term="blog" /><category term="kotlin" /><category term="coding" /><category term="kotlin_fundamentals" /><summary type="html"><![CDATA[Harness the power of sealed classes to write more expressive and safer code.]]></summary></entry><entry><title type="html">Kotlin Fundamentals : Data Classes</title><link href="https://www.albertlatacz.com/blog/kotlin-fundamentals-data-classes/" rel="alternate" type="text/html" title="Kotlin Fundamentals : Data Classes" /><published>2024-07-08T08:25:00+00:00</published><updated>2024-07-08T08:25:00+00:00</updated><id>https://www.albertlatacz.com/blog/kotlin-fundamentals-data-classes</id><content type="html" xml:base="https://www.albertlatacz.com/blog/kotlin-fundamentals-data-classes/"><![CDATA[<p>As software craftsmen, we constantly look for ways to write clean, concise code that is both easy to understand and maintain. 
One of Kotlin’s most powerful features that can help achieving that is the data class. Data class offer a concise way to create 
objects that serve as simple data containers, automatically providing essential functionality that would otherwise require 
extensive boilerplate code.</p>

<p>In this comprehensive guide, we’ll dive deep into Kotlin data classes, exploring their features, benefits, and best 
practices. We’ll cover from basic usage to advanced techniques, helping you use the full power of this fundamental 
Kotlin feature.</p>

<h1 id="what-is-a-data-class">What Is A Data Class?</h1>

<p>A data class is a class specifically designed to hold data rather than behavior. These classes automatically generate 
substantial boilerplate code that you would otherwise have to write yourself. This includes methods like <code class="language-plaintext highlighter-rouge">toString()</code>, <code class="language-plaintext highlighter-rouge">equals()</code>, 
<code class="language-plaintext highlighter-rouge">hashCode()</code>, and <code class="language-plaintext highlighter-rouge">copy()</code>.</p>

<h2 id="syntax">Syntax</h2>

<p>To declare a data class you use the <code class="language-plaintext highlighter-rouge">data</code> keyword before the class definition. Here’s the basic syntax:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
</pre></td><td class="rouge-code"><pre><span class="kd">data class</span> <span class="nc">Person</span><span class="p">(</span><span class="kd">val</span> <span class="py">name</span><span class="p">:</span> <span class="nc">String</span><span class="p">,</span> <span class="kd">var</span> <span class="py">age</span><span class="p">:</span> <span class="nc">Int</span><span class="p">)</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>Notice that you may define immutable (preferred, defined with <code class="language-plaintext highlighter-rouge">val</code>) as well as mutable (<code class="language-plaintext highlighter-rouge">var</code>) properties.</p>

<h2 id="features">Features</h2>

<p>Kotlin’s data classes come with several very useful features:</p>

<h3 id="autogenerated-utility-functions">Autogenerated Utility Functions</h3>

<p>Data classes automatically provide implementations for:</p>
<ul>
  <li><code class="language-plaintext highlighter-rouge">toString()</code> for readable string representation</li>
  <li><code class="language-plaintext highlighter-rouge">equals()</code> for structural equality comparison</li>
  <li><code class="language-plaintext highlighter-rouge">hashCode()</code> for consistent hash code generation</li>
  <li><code class="language-plaintext highlighter-rouge">copy()</code> for easy creation of modified instances</li>
</ul>

<p>Having those methods generated ensures consistent and correct implementation as well as reduces boilerplate.</p>

<h3 id="concise-syntax">Concise Syntax</h3>

<p>Data classes significantly reduce boilerplate code. A single line can replace many lines in other languages:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
</pre></td><td class="rouge-code"><pre><span class="kd">data class</span> <span class="nc">Product</span><span class="p">(</span><span class="kd">val</span> <span class="py">id</span><span class="p">:</span> <span class="nc">Int</span><span class="p">,</span> <span class="kd">val</span> <span class="py">name</span><span class="p">:</span> <span class="nc">String</span><span class="p">,</span> <span class="kd">val</span> <span class="py">price</span><span class="p">:</span> <span class="nc">Double</span><span class="p">)</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>Additionally, to concise syntax making code more clean and understandable, it makes the intent of the class
(to hold data) immediately clear.</p>

<h3 id="destructuring-declarations">Destructuring Declarations</h3>
<p>Data classes support component functions (<code class="language-plaintext highlighter-rouge">componentN()</code>), allowing easy destructuring:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
</pre></td><td class="rouge-code"><pre><span class="kd">val</span> <span class="p">(</span><span class="py">name</span><span class="p">,</span> <span class="py">age</span><span class="p">)</span> <span class="p">=</span> <span class="nc">Person</span><span class="p">(</span><span class="s">"Alice"</span><span class="p">,</span> <span class="mi">25</span><span class="p">)</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>The syntax enables easy unpacking of object properties, which can enhance readability in certain situations.</p>

<h3 id="immutability-support">Immutability Support</h3>
<p>Data classes can be made immutable by using ‘val’ for properties:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
</pre></td><td class="rouge-code"><pre><span class="kd">data class</span> <span class="nc">ImmutablePerson</span><span class="p">(</span><span class="kd">val</span> <span class="py">name</span><span class="p">:</span> <span class="nc">String</span><span class="p">,</span> <span class="kd">val</span> <span class="py">age</span><span class="p">:</span> <span class="nc">Int</span><span class="p">)</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<h3 id="inheritance">Inheritance</h3>
<p>Data classes are final, but they can extend classes or implement interfaces</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
</pre></td><td class="rouge-code"><pre><span class="kd">interface</span> <span class="nc">Printable</span>
<span class="kd">data class</span> <span class="nc">Report</span><span class="p">(</span><span class="kd">val</span> <span class="py">title</span><span class="p">:</span> <span class="nc">String</span><span class="p">)</span> <span class="p">:</span> <span class="nc">Printable</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>The above features make data classes in Kotlin powerful tools for creating simple, efficient, and functional data-holding 
objects with minimal code.</p>

<h2 id="advanced-features-and-customization">Advanced Features and Customization</h2>

<h3 id="overriding-generated-functions">Overriding Generated Functions</h3>

<p>While Kotlin generates most of the boilerplate code, you can still customize the behavior of data classes by overriding the generated methods. For example:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
</pre></td><td class="rouge-code"><pre><span class="kd">data class</span> <span class="nc">Person</span><span class="p">(</span><span class="kd">val</span> <span class="py">name</span><span class="p">:</span> <span class="nc">String</span><span class="p">,</span> <span class="kd">val</span> <span class="py">age</span><span class="p">:</span> <span class="nc">Int</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">override</span> <span class="k">fun</span> <span class="nf">toString</span><span class="p">():</span> <span class="nc">String</span> <span class="p">{</span>
        <span class="k">return</span> <span class="s">"Person's name is $name and age is $age"</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<h3 id="named-and-default-arguments">Named and Default Arguments</h3>

<p>Kotlin allows you to provide default values for properties and use named arguments, making the creation of instances more flexible:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
</pre></td><td class="rouge-code"><pre><span class="kd">data class</span> <span class="nc">Person</span><span class="p">(</span><span class="kd">val</span> <span class="py">name</span><span class="p">:</span> <span class="nc">String</span> <span class="p">=</span> <span class="s">"Unknown"</span><span class="p">,</span> <span class="kd">val</span> <span class="py">age</span><span class="p">:</span> <span class="nc">Int</span> <span class="p">=</span> <span class="mi">0</span><span class="p">)</span>

<span class="nf">println</span><span class="p">(</span><span class="nc">Person</span><span class="p">())</span>                <span class="c1">// Prints "Person(name=Unknown, age=0)"</span>
<span class="nf">println</span><span class="p">(</span><span class="nc">Person</span><span class="p">(</span><span class="n">name</span> <span class="p">=</span> <span class="s">"Alice"</span><span class="p">))</span>  <span class="c1">// Prints "Person(name=Alice, age=0)"</span>
<span class="nf">println</span><span class="p">(</span><span class="nc">Person</span><span class="p">(</span><span class="n">age</span> <span class="p">=</span> <span class="mi">25</span><span class="p">))</span>        <span class="c1">// Prints "Person(name=Unknown, age=25)"</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<h3 id="used-with-sealed-classes">Used With Sealed Classes</h3>

<p>Sealed classes and data classes can be used together to represent complex data hierarchies. A sealed class restricts the hierarchy to a limited set of subclasses, which can be data classes:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td class="rouge-code"><pre><span class="k">sealed</span> <span class="kd">class</span> <span class="nc">Shape</span> <span class="p">{</span>
    <span class="kd">data class</span> <span class="nc">Circle</span><span class="p">(</span><span class="kd">val</span> <span class="py">radius</span><span class="p">:</span> <span class="nc">Double</span><span class="p">)</span> <span class="p">:</span> <span class="nc">Shape</span><span class="p">()</span>
    <span class="kd">data class</span> <span class="nc">Rectangle</span><span class="p">(</span><span class="kd">val</span> <span class="py">width</span><span class="p">:</span> <span class="nc">Double</span><span class="p">,</span> <span class="kd">val</span> <span class="py">height</span><span class="p">:</span> <span class="nc">Double</span><span class="p">)</span> <span class="p">:</span> <span class="nc">Shape</span><span class="p">()</span>
    <span class="kd">data class</span> <span class="nc">Square</span><span class="p">(</span><span class="kd">val</span> <span class="py">side</span><span class="p">:</span> <span class="nc">Double</span><span class="p">)</span> <span class="p">:</span> <span class="nc">Shape</span><span class="p">()</span>
<span class="p">}</span>

<span class="k">fun</span> <span class="nf">describeShape</span><span class="p">(</span><span class="n">shape</span><span class="p">:</span> <span class="nc">Shape</span><span class="p">)</span> <span class="p">=</span> <span class="k">when</span> <span class="p">(</span><span class="n">shape</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">is</span> <span class="nc">Circle</span> <span class="p">-&gt;</span> <span class="s">"Circle with radius ${shape.radius}"</span>
    <span class="k">is</span> <span class="nc">Rectangle</span> <span class="p">-&gt;</span> <span class="s">"Rectangle with width ${shape.width} and height ${shape.height}"</span>
    <span class="k">is</span> <span class="nc">Square</span> <span class="p">-&gt;</span> <span class="s">"Square with side ${shape.side}"</span>
<span class="p">}</span>

<span class="nf">println</span><span class="p">(</span><span class="nf">describeShape</span><span class="p">(</span><span class="nc">Square</span><span class="p">(</span><span class="mf">12.0</span><span class="p">)))</span> <span class="c1">// Prints "Square with side 12.0"</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<h1 id="best-practices">Best Practices</h1>

<h3 id="prefer-immutability">Prefer Immutability</h3>

<p>Although data classes allow defining mutable properties (using <code class="language-plaintext highlighter-rouge">var</code>), they can lead to unexpected behavior and bugs as 
described in <a href="/blog/kotlin-fundamentals-explicit-mutability/">Explicit Mutability post</a>. Whenever possible, 
use <code class="language-plaintext highlighter-rouge">val</code> to declare properties in data classes to make them immutable. This ensures that the state of the object 
cannot be changed after it is created, promoting safer and more predictable code.</p>

<h3 id="avoid-complex-logic-in-data-classes">Avoid Complex Logic in Data Classes</h3>

<p>Data classes are intended to hold data, so avoid including complex logic within them. Keep them focused on representing 
the state and use other classes or functions to handle the behavior.</p>

<h3 id="leverage-destructuring-declarations">Leverage Destructuring Declarations</h3>

<p>Destructuring declarations can simplify your code when you need to extract properties from a data class instance.
Use them to enhance readability and reduce boilerplate.</p>

<h3 id="keep-size-under-control">Keep Size Under Control</h3>

<p>While data classes are convenient, avoid creating excessively large data classes with many properties. 
This can make the class difficult to manage and understand. Consider breaking it down into smaller, more focused classes.</p>

<h1 id="conclusion">Conclusion</h1>

<p>Kotlin’s data classes are a powerful feature that significantly reduces boilerplate code and simplifies the development 
process. They are designed to hold data and automatically generate useful methods, promoting immutability and providing 
a clean, expressive syntax. By leveraging data classes in your Kotlin applications, you can write more concise, readable, 
and maintainable code. Following best practices and understanding the common pitfalls, you help can harness the full potential of 
Kotlin data classes and improve the quality of your codebase.</p>]]></content><author><name>Albert Latacz</name></author><category term="blog" /><category term="kotlin" /><category term="coding" /><category term="kotlin_fundamentals" /><summary type="html"><![CDATA[Explore how data classes can boost your productivity and code readability.]]></summary></entry><entry><title type="html">Kotlin Fundamentals : Extension Functions</title><link href="https://www.albertlatacz.com/blog/kotlin-fundamentals-extension-functions/" rel="alternate" type="text/html" title="Kotlin Fundamentals : Extension Functions" /><published>2024-07-03T08:25:00+00:00</published><updated>2024-07-03T08:25:00+00:00</updated><id>https://www.albertlatacz.com/blog/kotlin-fundamentals-extension-functions</id><content type="html" xml:base="https://www.albertlatacz.com/blog/kotlin-fundamentals-extension-functions/"><![CDATA[<p>Kotlin’s extension functions stand out as one of the language most powerful features. These functions allow developers to 
add new functionality to existing classes without modifying their source code or inheriting from them. Unique capability 
enables cleaner, more expressive syntax by extending classes with custom code and works, even those from external libraries 
or the Java standard library. In this blog post we’ll dive into extension functions exploring their benefits and how to use them.</p>

<h1 id="what-are-extension-functions">What Are Extension Functions?</h1>

<p>An extension function is a way to add a new function to a class from outside of it. This means you can extend 
the functionality of classes you don’t own or can’t modify (including classes from the standard library as well as third-party libraries).</p>

<p>The basic syntax for an extension function is:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
</pre></td><td class="rouge-code"><pre><span class="k">fun</span> <span class="nc">Receiver</span><span class="p">.</span><span class="nf">functionName</span><span class="p">()</span> <span class="p">{}</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>Here, <code class="language-plaintext highlighter-rouge">Receiver</code> is the type you’re extending, and <code class="language-plaintext highlighter-rouge">functionName</code> is the name of your new function.</p>

<h1 id="why-use-extension-functions">Why Use Extension Functions?</h1>

<p>Using extension functions offer many benefits but here are some to consider:</p>

<ul>
  <li><strong>Code organization</strong> - They allow you to keep related functions together, even if they operate on different types.</li>
  <li><strong>Utility functions</strong> - They are great for creating utility functions that operate on existing types.</li>
  <li><strong>Context-specific functionality</strong> - You can add methods that are relevant only in certain contexts.</li>
  <li><strong>API design</strong> - Extension functions can be used to design more fluent and expressive APIs.</li>
  <li><strong>Readability</strong> - Extension functions can make code more readable and expressive (e.g. when creating domain-specific language).</li>
</ul>

<h1 id="why-not-just-member-functions">Why Not Just Member Functions?</h1>

<p>You might be wondering why use extension functions instead of just adding a member function to the class? There are several reasons:</p>

<ul>
  <li><strong>External classes</strong> - You can’t modify external classes (e.g. from libraries) to add new methods.</li>
  <li><strong>Separation of concerns</strong> - Extension functions allow you to keep utility functions separate from the main class definition.</li>
  <li><strong>Contextual usage</strong> - You can define extensions only for the specific modules where they’re needed.</li>
</ul>

<p>It’s important to note though that extension functions are resolved statically.
They don’t actually modify the class they extend, and they can’t access private members of the class.</p>

<h2 id="examples">Examples</h2>

<p>Let’s start with some simple examples to illustrate how extension functions work:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
</pre></td><td class="rouge-code"><pre><span class="k">fun</span> <span class="nc">String</span><span class="p">.</span><span class="nf">exclaim</span><span class="p">()</span> <span class="p">=</span> <span class="s">"$this!"</span>
<span class="nf">println</span><span class="p">(</span><span class="s">"Hello"</span><span class="p">.</span><span class="nf">exclaim</span><span class="p">())</span> <span class="c1">// Prints "Hello!"</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>In this example we have added a new function <code class="language-plaintext highlighter-rouge">exclaim()</code> to the existing <code class="language-plaintext highlighter-rouge">String</code> class. We can now call this function on any String instance.</p>

<p>You can also define extensions functions with parameters (same as with standard functions):</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
</pre></td><td class="rouge-code"><pre><span class="k">fun</span> <span class="nc">Int</span><span class="p">.</span><span class="nf">isMultipleOf</span><span class="p">(</span><span class="n">number</span><span class="p">:</span> <span class="nc">Int</span><span class="p">)</span> <span class="p">=</span> <span class="k">this</span> <span class="p">%</span> <span class="n">number</span> <span class="p">==</span> <span class="mi">0</span>
<span class="nf">println</span><span class="p">(</span><span class="mi">12</span><span class="p">.</span><span class="nf">isMultipleOf</span><span class="p">(</span><span class="mi">3</span><span class="p">))</span><span class="c1">// Prints "true"</span>
<span class="nf">println</span><span class="p">(</span><span class="mi">12</span><span class="p">.</span><span class="nf">isMultipleOf</span><span class="p">(</span><span class="mi">5</span><span class="p">))</span><span class="c1">// Prints "false"</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<h1 id="nullability-and-extension-functions">Nullability And Extension Functions</h1>

<p>Kotlin’s null safety is one of its fundamental features as we explored in <a href="/blog/kotlin-fundamentals-null-safety/">Null Safety post</a>, and 
it works seamlessly with extension functions. You can define extension functions on nullable types:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
</pre></td><td class="rouge-code"><pre><span class="k">fun</span> <span class="nf">String</span><span class="o">?.</span><span class="nf">orEmpty</span><span class="p">()</span> <span class="p">=</span> <span class="k">this</span> <span class="o">?:</span> <span class="s">""</span>
<span class="kd">val</span> <span class="py">someValue</span><span class="p">:</span> <span class="nc">String</span><span class="p">?</span> <span class="p">=</span> <span class="k">null</span>
<span class="nf">println</span><span class="p">(</span><span class="n">someValue</span><span class="p">.</span><span class="nf">orEmpty</span><span class="p">())</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>This is particularly useful for providing default behaviors for null values.</p>

<h1 id="extension-properties">Extension Properties</h1>

<p>In addition to functions, Kotlin also allows you to define extension properties:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
</pre></td><td class="rouge-code"><pre><span class="kd">val</span> <span class="py">String</span><span class="p">.</span><span class="n">lastChar</span><span class="p">:</span> <span class="nc">Char</span>
    <span class="k">get</span><span class="p">()</span> <span class="p">=</span> <span class="k">this</span><span class="p">[</span><span class="n">length</span> <span class="p">-</span> <span class="mi">1</span><span class="p">]</span>

<span class="nf">println</span><span class="p">(</span><span class="s">"Kotlin"</span><span class="p">.</span><span class="n">lastChar</span><span class="p">)</span>  <span class="c1">// Outputs: n</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<h1 id="companion-object-extensions">Companion Object Extensions</h1>

<p>You can even extend companion objects, allowing you to add methods to classes or interfaces:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
6
7
</pre></td><td class="rouge-code"><pre><span class="kd">class</span> <span class="nc">MyClass</span> <span class="p">{</span>
    <span class="k">companion</span> <span class="k">object</span>
<span class="p">}</span>

<span class="k">fun</span> <span class="nc">MyClass</span><span class="p">.</span><span class="nc">Companion</span><span class="p">.</span><span class="nf">greeting</span><span class="p">()</span> <span class="p">=</span> <span class="s">"Hello from companion object extension"</span>

<span class="nf">println</span><span class="p">(</span><span class="nc">MyClass</span><span class="p">.</span><span class="nf">greeting</span><span class="p">())</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>This can be useful for adding utility functions that are related to a class but don’t need an instance of the class.</p>

<h1 id="generic-extensions">Generic Extensions</h1>

<p>Extension functions can also be generic, allowing you to write more flexible and reusable code:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
</pre></td><td class="rouge-code"><pre><span class="k">fun</span> <span class="p">&lt;</span><span class="nc">T</span><span class="p">&gt;</span> <span class="nc">T</span><span class="p">.</span><span class="nf">println</span><span class="p">()</span> <span class="p">=</span> <span class="nf">println</span><span class="p">(</span><span class="k">this</span><span class="p">)</span>

<span class="mi">5</span><span class="p">.</span><span class="nf">println</span><span class="p">()</span>           <span class="c1">// Outputs: 5</span>
<span class="s">"Hello"</span><span class="p">.</span><span class="nf">println</span><span class="p">()</span>     <span class="c1">// Outputs: Hello</span>
<span class="nf">listOf</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">).</span><span class="nf">println</span><span class="p">()</span>  <span class="c1">// Outputs: [1, 2, 3]</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>This example defines a <code class="language-plaintext highlighter-rouge">println()</code> extension function that works on any type.</p>

<h1 id="infix-notation">Infix Notation</h1>

<p>It is also possible to define extension functions with infix notation which, in certain situations, can lead to more readable code:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
</pre></td><td class="rouge-code"><pre><span class="k">infix</span> <span class="k">fun</span> <span class="nc">Int</span><span class="p">.</span><span class="nf">isMultipleOf</span><span class="p">(</span><span class="n">number</span><span class="p">:</span> <span class="nc">Int</span><span class="p">)</span> <span class="p">=</span> <span class="k">this</span> <span class="p">%</span> <span class="n">number</span> <span class="p">==</span> <span class="mi">0</span>
<span class="nf">println</span><span class="p">(</span><span class="mi">10</span> <span class="n">isMultipleOf</span> <span class="mi">5</span><span class="p">)</span>  <span class="c1">// Outputs: true</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">infix</code> keyword allows you to call the function using infix notation (without the dot and parentheses).</p>

<h1 id="common-use-case-examples">Common Use Case Examples</h1>

<p>Here are some common use case examples for using extension functions.</p>

<h3 id="dsl-creation">DSL Creation</h3>

<p>Extension functions are often used in creating domain-specific languages (DSLs) in Kotlin.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
</pre></td><td class="rouge-code"><pre><span class="kd">class</span> <span class="nc">Html</span> <span class="k">private</span> <span class="k">constructor</span><span class="p">()</span> <span class="p">{</span>
    <span class="k">companion</span> <span class="k">object</span> <span class="p">{</span>
        <span class="k">fun</span> <span class="nf">html</span><span class="p">(</span><span class="n">fn</span><span class="p">:</span> <span class="nc">Html</span><span class="p">.()</span> <span class="p">-&gt;</span> <span class="nc">Unit</span><span class="p">)</span> <span class="p">=</span>
            <span class="nc">Html</span><span class="p">().</span><span class="nf">apply</span><span class="p">(</span><span class="n">fn</span><span class="p">).</span><span class="nf">render</span><span class="p">()</span>
    <span class="p">}</span>

    <span class="k">private</span> <span class="kd">var</span> <span class="py">content</span><span class="p">:</span> <span class="nc">String</span> <span class="p">=</span> <span class="s">""</span>
    <span class="k">internal</span> <span class="k">fun</span> <span class="nf">append</span><span class="p">(</span><span class="n">value</span><span class="p">:</span> <span class="nc">String</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">content</span> <span class="p">+=</span> <span class="n">value</span>
    <span class="p">}</span>

    <span class="k">fun</span> <span class="nf">render</span><span class="p">()</span> <span class="p">=</span> <span class="s">"&lt;html&gt;$content&lt;/html&gt;"</span>
<span class="p">}</span>

<span class="kd">class</span> <span class="nc">Body</span> <span class="p">{</span>
    <span class="k">private</span> <span class="kd">var</span> <span class="py">content</span><span class="p">:</span> <span class="nc">String</span> <span class="p">=</span> <span class="s">""</span>
    <span class="k">internal</span> <span class="k">fun</span> <span class="nf">append</span><span class="p">(</span><span class="n">value</span><span class="p">:</span> <span class="nc">String</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">content</span> <span class="p">+=</span> <span class="n">value</span>
    <span class="p">}</span>
    <span class="k">internal</span> <span class="k">fun</span> <span class="nf">render</span><span class="p">()</span> <span class="p">=</span> <span class="s">"&lt;body&gt;$content&lt;/body&gt;"</span>
<span class="p">}</span>

<span class="k">fun</span> <span class="nc">Html</span><span class="p">.</span><span class="nf">body</span><span class="p">(</span><span class="n">fn</span><span class="p">:</span> <span class="nc">Body</span><span class="p">.()</span> <span class="p">-&gt;</span> <span class="nc">Unit</span><span class="p">)</span> <span class="p">=</span> <span class="nf">append</span><span class="p">(</span><span class="nc">Body</span><span class="p">().</span><span class="nf">apply</span><span class="p">(</span><span class="n">fn</span><span class="p">).</span><span class="nf">render</span><span class="p">())</span>
<span class="k">fun</span> <span class="nc">Body</span><span class="p">.</span><span class="nf">p</span><span class="p">(</span><span class="n">text</span><span class="p">:</span> <span class="nc">String</span><span class="p">)</span> <span class="p">=</span> <span class="nf">append</span><span class="p">(</span><span class="s">"&lt;p&gt;$text&lt;/p&gt;"</span><span class="p">)</span>
<span class="k">fun</span> <span class="nc">Body</span><span class="p">.</span><span class="nf">a</span><span class="p">(</span><span class="n">href</span><span class="p">:</span> <span class="nc">String</span><span class="p">,</span> <span class="n">text</span><span class="p">:</span> <span class="nc">String</span><span class="p">)</span> <span class="p">=</span> <span class="nf">append</span><span class="p">(</span><span class="s">"&lt;a href='$href'&gt;$text&lt;/a&gt;"</span><span class="p">)</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>This example demonstrates how extension functions can be used to create a DSL for HTML generation.</p>

<h3 id="string-manipulation">String Manipulation</h3>

<p>Adding utility functions for common string operations.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
</pre></td><td class="rouge-code"><pre><span class="k">fun</span> <span class="nc">String</span><span class="p">.</span><span class="nf">removeFirstAndLast</span><span class="p">()</span> <span class="p">=</span> <span class="nf">substring</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="n">length</span> <span class="p">-</span> <span class="mi">1</span><span class="p">)</span>
<span class="nf">println</span><span class="p">(</span><span class="s">"Hello"</span><span class="p">.</span><span class="nf">removeFirstAndLast</span><span class="p">())</span>  <span class="c1">// Outputs: ell</span>

</pre></td></tr></tbody></table></code></pre></div></div>

<h3 id="collection-operations">Collection Operations</h3>

<p>Adding custom operations to collections.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
</pre></td><td class="rouge-code"><pre><span class="k">fun</span> <span class="p">&lt;</span><span class="nc">T</span><span class="p">&gt;</span> <span class="nf">List</span><span class="p">&lt;</span><span class="nc">T</span><span class="p">&gt;.</span><span class="nf">secondOrNull</span><span class="p">():</span> <span class="nc">T</span><span class="p">?</span> <span class="p">=</span> <span class="k">if</span> <span class="p">(</span><span class="n">size</span> <span class="p">&lt;</span> <span class="mi">2</span><span class="p">)</span> <span class="k">null</span> <span class="k">else</span> <span class="k">this</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>

<span class="nf">println</span><span class="p">(</span><span class="nf">listOf</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">).</span><span class="nf">secondOrNull</span><span class="p">())</span>  <span class="c1">// Outputs: 2</span>
<span class="nf">println</span><span class="p">(</span><span class="nf">listOf</span><span class="p">(</span><span class="mi">1</span><span class="p">).</span><span class="nf">secondOrNull</span><span class="p">())</span>        <span class="c1">// Outputs: null</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<h3 id="standard-library-examples">Standard Library Examples</h3>

<p>Kotlin’s standard library makes extensive use of extension functions. Some examples include:</p>
<ul>
  <li><code class="language-plaintext highlighter-rouge">let</code>, <code class="language-plaintext highlighter-rouge">apply</code>, <code class="language-plaintext highlighter-rouge">run</code>, <code class="language-plaintext highlighter-rouge">with</code>, and <code class="language-plaintext highlighter-rouge">also</code> for scoping and object manipulation</li>
  <li><code class="language-plaintext highlighter-rouge">forEach</code>, <code class="language-plaintext highlighter-rouge">map</code>, <code class="language-plaintext highlighter-rouge">filter</code>, etc., for collections</li>
  <li><code class="language-plaintext highlighter-rouge">last</code>, <code class="language-plaintext highlighter-rouge">substring</code> and other various string manipulation functions</li>
</ul>

<p>Understanding these can help you write more idiomatic Kotlin code and make better use of the language’s features.</p>

<h1 id="best-practices-considerations-and-limitations">Best Practices, Considerations and Limitations</h1>

<p>While extension functions are very powerful, here are some best practices and limitations to keep in mind:</p>

<ul>
  <li><strong>Don’t overuse</strong>: Not everything needs to be an extension function. Use them when they genuinely improve readability or organization.</li>
  <li><strong>Naming conventions</strong>: Follow naming conventions to avoid confusion. For example, don’t give an extension function the same name as a member function unless you’re intentionally overloading it.</li>
  <li><strong>Use for utility functions</strong>: Extension functions are great for utility functions that operate on existing types.</li>
  <li><strong>No override of extension functions</strong>: You can’t override extension functions. If a class has a member function with the same name and signature as an extension function, the member function will always take precedence.</li>
  <li><strong>Shadowing</strong>: If an extension function has the same name and signature as a member function, the member function will be used instead of the extension function.</li>
  <li><strong>No access to private members</strong>: Extension functions can’t access private or protected members of the class they’re extending.</li>
</ul>

<h1 id="conclusion">Conclusion</h1>

<p>Extension functions are a powerful feature in Kotlin that can significantly enhance code readability, organization, and reusability. They allow developers to extend existing classes with new functionality without modifying their source code, which is particularly useful when working with classes from external libraries or the standard library.</p>

<p>By using extension functions and following best practices, you can create more expressive and maintainable code. They’re particularly useful for utility functions, DSL creation, and adding convenience methods to existing types.</p>

<p>As with any powerful feature, it’s important to use extension functions thoughtfully. When used well, they can make your Kotlin code more concise, readable, and enjoyable to work with.</p>

<p>Whether you’re new to Kotlin or an experienced developer, mastering extension functions can significantly improve your coding skills and help you write more elegant and efficient code.</p>]]></content><author><name>Albert Latacz</name></author><category term="blog" /><category term="kotlin" /><category term="coding" /><category term="kotlin_fundamentals" /><summary type="html"><![CDATA[Learn now to write more clear, expressive and reusable code with extension functions.]]></summary></entry><entry><title type="html">Kotlin Fundamentals : Explicit Mutability</title><link href="https://www.albertlatacz.com/blog/kotlin-fundamentals-explicit-mutability/" rel="alternate" type="text/html" title="Kotlin Fundamentals : Explicit Mutability" /><published>2024-06-25T08:25:00+00:00</published><updated>2024-06-25T08:25:00+00:00</updated><id>https://www.albertlatacz.com/blog/kotlin-fundamentals-explicit-mutability</id><content type="html" xml:base="https://www.albertlatacz.com/blog/kotlin-fundamentals-explicit-mutability/"><![CDATA[<p>One of the hardest concepts to get right when programming is managing state and controlling how data changes. 
Which language we use can be crucial for writing clean, maintainable, and bug-free code. 
Kotlin, a modern programming language, includes in the toolbelt of it’s fundamental concepts a powerful feature known as explicit mutability. 
This feature, implemented through the use of <code class="language-plaintext highlighter-rouge">val</code> and <code class="language-plaintext highlighter-rouge">var</code> keywords, provides developers with fine-grained control over data mutability. 
In this blog post we’ll explore the ins and outs of explicit mutability in Kotlin, its benefits, best practices, and highlight briefly how it compares to other languages.</p>

<h1 id="understanding-mutability">Understanding Mutability</h1>

<p>Before we dive into Kotlin’s approach, let’s briefly discuss what mutability means in programming. 
In simple terms mutability refers to the ability to change or modify data after it’s been created. 
Mutable data can be altered, while immutable data remains constant throughout its lifetime.</p>

<h1 id="kotlins-approach-val-and-var">Kotlin’s Approach: val and var</h1>

<p>Kotlin has two keywords for variable declaration: <code class="language-plaintext highlighter-rouge">val</code> and <code class="language-plaintext highlighter-rouge">var</code>. These keywords explicitly define whether a variable or field is immutable (val) or mutable (var).</p>
<ul>
  <li><strong>val (Value) - Immutable References:</strong>
 When you declare a variable with ‘val’, you’re creating an immutable reference. This means that once a value is assigned to the variable, it cannot be reassigned. It’s similar to using the <code class="language-plaintext highlighter-rouge">final</code> keyword in Java. For example:
    <div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
</pre></td><td class="rouge-code"><pre> <span class="kd">val</span> <span class="py">name</span> <span class="p">=</span> <span class="s">"Alice"</span>
 <span class="c1">// name = "Bob"  // Compilation error</span>
</pre></td></tr></tbody></table></code></pre></div>    </div>
  </li>
  <li><strong>var (Variable) - Mutable References:</strong>
 Variables and fields declared with ‘var’ are mutable, meaning their value can be changed after initial assignment. Example:
    <div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
</pre></td><td class="rouge-code"><pre> <span class="kd">var</span> <span class="py">age</span> <span class="p">=</span> <span class="mi">25</span>
 <span class="n">age</span> <span class="p">=</span> <span class="mi">26</span>  <span class="c1">// This is perfectly valid</span>
</pre></td></tr></tbody></table></code></pre></div>    </div>
  </li>
</ul>

<h1 id="why-explicit-mutability">Why Explicit Mutability?</h1>

<h3 id="code-clarity">Code Clarity</h3>
<p>By using <code class="language-plaintext highlighter-rouge">val</code> and <code class="language-plaintext highlighter-rouge">var</code>, you’re making your intentions clear to your future self and other developers. Anyone reading the code can immediately understand whether a variable is meant to be changed or not.</p>

<h3 id="preventing-accidental-modifications">Preventing Accidental Modifications</h3>
<p>Using ‘val’ for variables that shouldn’t change helps prevent accidental modifications. The compiler will catch any attempts to reassign a ‘val’ variable, reducing the risk of unintended side effects.</p>

<h3 id="thread-safety">Thread Safety</h3>
<p>Immutable data is inherently thread-safe. When you’re working with concurrent code, using immutable data wherever possible can help avoid race conditions and other concurrency issues.</p>

<h3 id="functional-programming-support">Functional Programming Support</h3>
<p>Kotlin supports some of the functional programming concepts, and the use of immutable data aligns well with functional programming principles. It encourages writing pure functions and promotes easier reasoning about code behavior and state mutations.</p>

<h2 id="immutability-vs-read-only">Immutability vs. Read-Only</h2>

<p>It’s important to understand that ‘val’ creates a read-only reference, which is not always the same as true immutability. Let’s explore this concept further:</p>

<h3 id="immutable-references-to-mutable-objects">Immutable References to Mutable Objects</h3>
<p>When you use ‘val’ with a mutable object, the reference is immutable, but the object’s internal state can still be modified.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
</pre></td><td class="rouge-code"><pre><span class="kd">val</span> <span class="py">list</span> <span class="p">=</span> <span class="nf">mutableListOf</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
<span class="n">list</span><span class="p">.</span><span class="nf">add</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>  <span class="c1">// This is valid, as we're modifying the list's content, not the reference</span>
<span class="c1">// list = mutableListOf(5, 6)  // This would be a compilation error</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>In the example above the list reference is read only byt list itself is mutable.</p>

<h3 id="smart-casts-and-immutability">Smart Casts and Immutability</h3>
<p>Kotlin’s smart cast feature works with ‘val’ declarations but not with ‘var’.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
6
</pre></td><td class="rouge-code"><pre><span class="kd">var</span> <span class="py">mutableVar</span><span class="p">:</span> <span class="nc">Any</span> <span class="p">=</span> <span class="s">""</span>
<span class="k">fun</span> <span class="nf">failingSmartCastOfVar</span><span class="p">()</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">mutableVar</span> <span class="k">is</span> <span class="nc">String</span><span class="p">)</span> <span class="p">{</span>
        <span class="nf">print</span><span class="p">(</span><span class="n">mutableVar</span><span class="p">.</span><span class="n">length</span><span class="p">)</span> <span class="c1">// Compilation failure</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>The example above will fail to compile because the compiler can guarantee that a ‘val’ reference won’t change between the type check and its usage.</p>

<h3 id="properties-in-classes">Properties in Classes</h3>
<p>When declaring properties in a class, ‘val’ creates a read-only property with a generated getter, while ‘var’ creates a mutable property with both a getter and a setter.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
</pre></td><td class="rouge-code"><pre><span class="kd">class</span> <span class="nc">Person</span><span class="p">(</span>
    <span class="kd">val</span> <span class="py">name</span><span class="p">:</span> <span class="nc">String</span><span class="p">,</span>  <span class="c1">// Read-only property (has a getter)</span>
    <span class="kd">var</span> <span class="py">age</span><span class="p">:</span> <span class="nc">Int</span>      <span class="c1">// Mutable property (has both getter and setter)</span>
<span class="p">)</span> 
</pre></td></tr></tbody></table></code></pre></div></div>

<h1 id="best-practices-and-consideration-when-using-valvar">Best Practices And Consideration When Using val/var</h1>

<h3 id="prefer-val-by-default">Prefer ‘val’ By Default</h3>
<p>Start by declaring all variables with ‘val’. Only change to ‘var’ if you need to reassign the variable later. This approach, known as “immutability by default,” helps create more predictable and maintainable code.</p>

<h3 id="use-var-judiciously">Use ‘var’ Judiciously</h3>
<p>When you do need mutable state, use ‘var’. But try to limit the scope of mutable variables as much as possible. Consider if you can make the variable local to a function instead of a class property.</p>

<h3 id="immutable-collections">Immutable Collections</h3>
<p>Kotlin provides both mutable and immutable versions of collections.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
</pre></td><td class="rouge-code"><pre><span class="kd">val</span> <span class="py">immutableList</span> <span class="p">=</span> <span class="nf">listOf</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
<span class="kd">val</span> <span class="py">mutableList</span> <span class="p">=</span> <span class="nf">mutableListOf</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>Prefer using immutable collections (List, Set, Map) over their mutable counterparts (MutableList, MutableSet, MutableMap) when the collection doesn’t need to be modified.
Use mutable collections in limited scope and not return them, e.g. only in the body of the function but convert to immutable before returning.</p>

<p>Additionally Kotlin offers a concise and efficient way to create immutable collections using builder functions <code class="language-plaintext highlighter-rouge">buildXXX</code>. Those higher-order functions allow you to construct collections using a mutable builders within its lambda, providing a clean syntax for adding elements conditionally or in loops. The resulting collection is immutable, e.g:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
</pre></td><td class="rouge-code"><pre><span class="nf">buildList</span> <span class="p">{</span>
    <span class="k">for</span> <span class="p">(</span><span class="n">i</span> <span class="k">in</span> <span class="mi">0</span><span class="o">..</span><span class="mi">10</span><span class="p">)</span> <span class="p">{</span>
        <span class="nf">add</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>Collection builder functions are particularly useful when you need to create complex collections based on certain logic or transformations, without the verbosity of creating a mutable collections and converting it afterward.</p>

<h3 id="data-classes-and-immutability">Data Classes and Immutability</h3>
<p>When creating data classes, consider making properties ‘val’ by default. If you need mutable properties, you can always use ‘var’, but immutable data classes are easier to work with and reason about.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
</pre></td><td class="rouge-code"><pre><span class="kd">data class</span> <span class="nc">User</span><span class="p">(</span>
    <span class="kd">val</span> <span class="py">id</span><span class="p">:</span> <span class="nc">Int</span><span class="p">,</span> 
    <span class="kd">val</span> <span class="py">name</span><span class="p">:</span> <span class="nc">String</span><span class="p">,</span> 
    <span class="kd">var</span> <span class="py">lastLoginDate</span><span class="p">:</span> <span class="nc">Date</span>
<span class="p">)</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<h3 id="const-val-for-compile-time-constants">Const Val for Compile-Time Constants</h3>
<p>For top-level or object declarations that are known at compile-time, use ‘const val’. This creates a true compile-time constant, which can be more efficient.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
</pre></td><td class="rouge-code"><pre><span class="kd">object</span> <span class="nc">Constants</span> <span class="p">{</span>
    <span class="k">const</span> <span class="kd">val</span> <span class="py">MAX_COUNT</span> <span class="p">=</span> <span class="mi">100</span>
<span class="p">}</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<h3 id="backing-properties">Backing Properties</h3>
<p>Sometimes you might want to expose a read-only property while keeping a mutable backing field. Kotlin allows this through backing properties:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
6
7
8
9
</pre></td><td class="rouge-code"><pre><span class="kd">class</span> <span class="nc">Counter</span> <span class="p">{</span>
    <span class="k">private</span> <span class="kd">var</span> <span class="py">_count</span> <span class="p">=</span> <span class="mi">0</span>
    
    <span class="kd">val</span> <span class="py">count</span> <span class="k">get</span><span class="p">()</span> <span class="p">=</span> <span class="n">_count</span>
    
    <span class="k">fun</span> <span class="nf">increment</span><span class="p">()</span> <span class="p">{</span>
        <span class="n">_count</span><span class="p">++</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<h3 id="delegated-properties">Delegated Properties</h3>
<p>Kotlin’s property delegation allows you to reuse common property patterns. You can create a read-only property that is calculated on-demand using ‘by lazy’:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
</pre></td><td class="rouge-code"><pre><span class="kd">val</span> <span class="py">expensiveComputation</span><span class="p">:</span> <span class="nc">Int</span> <span class="k">by</span> <span class="nf">lazy</span> <span class="p">{</span>
    <span class="nf">println</span><span class="p">(</span><span class="s">"Computing..."</span><span class="p">)</span>
    <span class="c1">// Complex computation here</span>
    <span class="mi">42</span>
<span class="p">}</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<h3 id="late-initialized-properties">Late-Initialized Properties</h3>
<p>Sometimes you need to have a non-null <code class="language-plaintext highlighter-rouge">var</code> property that’s initialized after the constructor. Kotlin provides the <code class="language-plaintext highlighter-rouge">lateinit</code> modifier for this:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td class="rouge-code"><pre><span class="kd">class</span> <span class="nc">MyTest</span> <span class="p">{</span>
    <span class="k">lateinit</span> <span class="kd">var</span> <span class="py">subject</span><span class="p">:</span> <span class="nc">String</span>

    <span class="nd">@BeforeTest</span>
    <span class="k">fun</span> <span class="nf">setup</span><span class="p">()</span> <span class="p">{</span>
        <span class="n">subject</span> <span class="p">=</span> <span class="s">"Some value"</span>
    <span class="p">}</span>

    <span class="nd">@Test</span> 
    <span class="k">fun</span> <span class="nf">testLength</span><span class="p">()</span> <span class="p">{</span>
        <span class="nf">assertEquals</span><span class="p">(</span><span class="n">subject</span><span class="p">.</span><span class="n">length</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<h3 id="inline-value-classes-and-immutability">Inline Value Classes and Immutability</h3>
<p>Kotlin’s <a href="https://kotlinlang.org/docs/inline-classes.html">inline value classes</a> are a great way to create type-safe wrappers with zero runtime overhead. These type of class can be used to wrap domain values and inherently immutable:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
6
7
8
9
</pre></td><td class="rouge-code"><pre><span class="nd">@JvmInline</span>
<span class="n">value</span> <span class="kd">class</span> <span class="nc">Password</span><span class="p">(</span>
    <span class="kd">val</span> <span class="py">value</span><span class="p">:</span> <span class="nc">String</span>
<span class="p">)</span>

<span class="nd">@Test</span>
<span class="k">fun</span> <span class="nf">`example</span> <span class="k">inline</span> <span class="kd">class</span> <span class="err">test`() {
    assert</span><span class="nc">Equals</span><span class="p">(</span><span class="nc">Password</span><span class="p">(</span><span class="s">"secret"</span><span class="p">).</span><span class="n">value</span><span class="p">,</span> <span class="s">"secret"</span><span class="p">)</span>
<span class="p">}</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<h1 id="challenges-and-considerations">Challenges and Considerations</h1>

<p>While Kotlin’s explicit mutability is a great feature, it’s not come without some challenges:</p>

<h3 id="learning-curve">Learning Curve</h3>
<p>Developers coming from languages without explicit mutability might need time to adjust to thinking about mutability for every variable they declare.</p>

<h3 id="overuse-of-var">Overuse of var</h3>
<p>Using var excessively can lead to code that is difficult to understand and maintain. To avoid this, always consider if a variable truly needs to be mutable and try to refactor your code to use val whenever possible.</p>

<h3 id="forgetting-to-use-immutable-collections">Forgetting to Use Immutable Collections</h3>
<p>It’s easy to default to mutable collections out of habit. However, mutable collections can introduce unexpected changes and bugs. Always evaluate if an immutable collection can be used instead.</p>

<h3 id="performance-considerations">Performance Considerations</h3>
<p>While immutability can lead to safer code, it can sometimes come with a performance cost, especially when working with large data structures that need frequent updates.</p>

<h1 id="conclusion">Conclusion</h1>

<p>Kotlin’s Explicit Mutability, implemented through ‘val’ and ‘var’, is a fundamental feature that promotes safer, more predictable code. By making immutability the default and requiring explicit declaration for mutable variables, 
Kotlin encourages developers to think carefully about state management in their applications.</p>

<p>As with any language feature, the key to leveraging Explicit Mutability effectively lies in understanding its nuances and applying it judiciously. By following best practices and considering 
the principles of immutability, developers can write Kotlin code that is not only functional but also maintainable and robust.</p>

<p>Whether you’re building Android apps, server-side applications, or multiplatform projects, mastering Kotlin’s approach to mutability 
will serve you well in creating high-quality software. So next time you’re declaring a variable in Kotlin, take a moment to consider: should it be a ‘val’ or a ‘var’? Your future self (and your team) will thank you for it.</p>]]></content><author><name>Albert Latacz</name></author><category term="blog" /><category term="kotlin" /><category term="coding" /><category term="kotlin_fundamentals" /><summary type="html"><![CDATA[Understand concepts of explicit mutability and write safer code with fewer bugs.]]></summary></entry><entry><title type="html">Kotlin Fundamentals : Null Safety</title><link href="https://www.albertlatacz.com/blog/kotlin-fundamentals-null-safety/" rel="alternate" type="text/html" title="Kotlin Fundamentals : Null Safety" /><published>2024-06-20T07:00:00+00:00</published><updated>2024-06-20T07:00:00+00:00</updated><id>https://www.albertlatacz.com/blog/kotlin-fundamentals-null-safety</id><content type="html" xml:base="https://www.albertlatacz.com/blog/kotlin-fundamentals-null-safety/"><![CDATA[<p>Null safety is one of the fundamental features of Kotlin, designed to eliminate the infamous NullPointerExceptions (NPE) 
that so plague developers.</p>

<p>This blog post will explore Kotlin’s null safety in detail, including its benefits, how it works, and practical examples 
to illustrate its application. Whether you are a seasoned developer or new to Kotlin, this comprehensive guide will help you understand and 
apply null safety guards effectively in your projects.</p>

<h1 id="the-problem-with-null-pointers">The Problem With Null Pointers</h1>
<p>Null pointers are a common source of bugs and crashes in many programming languages. In Java, for instance, dereferencing a null reference 
results in a NullPointerException (NPE). These exceptions can be difficult to track down and fix, especially in large codebases.</p>

<p>For more history have a look at the talk <a href="https://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare/">“Null References: The Billion Dollar Mistake”</a> by Tony Hoare, who describes the costly impact of null-related bugs.</p>

<h1 id="kotlins-approach-to-null-safety">Kotlin’s Approach to Null Safety</h1>
<p>Kotlin addresses the problem of null pointers by introducing a type system that differentiates between nullable and non-nullable types. This distinction 
allows Kotlin to enforce null checks at compile-time, significantly reducing the likelihood of NPEs.</p>

<p>Types are non-nullable by default. This means that a variable of type String cannot hold a null value:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
</pre></td><td class="rouge-code"><pre><span class="kd">var</span> <span class="py">nonNullableString</span><span class="p">:</span> <span class="nc">String</span> <span class="p">=</span> <span class="s">"Hello, Kotlin"</span>
<span class="c1">// nonNullableString = null // Compile-time error</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>To declare a variable that can hold a null value, you append a <code class="language-plaintext highlighter-rouge">?</code> to the type:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
</pre></td><td class="rouge-code"><pre><span class="kd">var</span> <span class="py">nullableString</span><span class="p">:</span> <span class="nc">String</span><span class="p">?</span> <span class="p">=</span> <span class="k">null</span>
<span class="n">nullableString</span> <span class="p">=</span> <span class="k">null</span> <span class="c1">// All good</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>By explicitly distinguishing between nullable and non-nullable types, Kotlin forces developers to think about nullability and handle it appropriately.</p>

<h3 id="safe-calls">Safe Calls</h3>
<p>Kotlin provides a safe call operator <code class="language-plaintext highlighter-rouge">?.</code> to handle nullable types safely. The safe call operator allows you to access properties and methods of a nullable 
object without risking an NPE:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
</pre></td><td class="rouge-code"><pre><span class="kd">val</span> <span class="py">length</span><span class="p">:</span> <span class="nc">Int</span><span class="p">?</span> <span class="p">=</span> <span class="n">nullableString</span><span class="o">?.</span><span class="n">length</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>In this example, <code class="language-plaintext highlighter-rouge">nullableString?.length</code> returns null if nullableString is <code class="language-plaintext highlighter-rouge">null</code>, otherwise it returns the length of the string. This prevents a potential NPE 
and makes the code more concise and readable.</p>

<h3 id="elvis-operator">Elvis Operator</h3>
<p>The Elvis operator <code class="language-plaintext highlighter-rouge">?:</code> is another useful construct for dealing with nullable types. It allows you to provide a default value in case a nullable expression evaluates 
to null:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
</pre></td><td class="rouge-code"><pre><span class="kd">val</span> <span class="py">length</span><span class="p">:</span> <span class="nc">Int</span> <span class="p">=</span> <span class="n">nullableString</span><span class="o">?.</span><span class="n">length</span> <span class="o">?:</span> <span class="mi">0</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>Here, if <code class="language-plaintext highlighter-rouge">nullableString</code> is <code class="language-plaintext highlighter-rouge">null</code>, the length will be set to 0. The Elvis operator is a concise way to handle null values and provide fallback logic.</p>

<h3 id="not-null-assertion">Not-Null Assertion</h3>
<p>Sometimes you might be certain that a nullable variable is not null at a particular point in your code. In such cases, you can use the not-null assertion operator <code class="language-plaintext highlighter-rouge">!!</code> to 
tell the compiler that the value is not null:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
</pre></td><td class="rouge-code"><pre><span class="kd">val</span> <span class="py">length</span><span class="p">:</span> <span class="nc">Int</span> <span class="p">=</span> <span class="n">nullableString</span><span class="o">!!</span><span class="p">.</span><span class="n">length</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>Use the not-null assertion operator with caution. If the variable is actually null, the application will throw an NPE at runtime, defeating the purpose of null safety! 
It is generally better to use safe calls and the Elvis operator to handle null values more gracefully.</p>

<h1 id="working-with-collections">Working With Collections</h1>
<p>Kotlin also provides null safety mechanisms for collections. You can declare collections of nullable or non-nullable types, and Kotlin’s type system ensures that you handle nullability correctly:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
</pre></td><td class="rouge-code"><pre><span class="kd">val</span> <span class="py">nonNullableList</span><span class="p">:</span> <span class="nc">List</span><span class="p">&lt;</span><span class="nc">String</span><span class="p">&gt;</span> <span class="p">=</span> <span class="nf">listOf</span><span class="p">(</span><span class="s">"Kotlin"</span><span class="p">,</span> <span class="s">"Java"</span><span class="p">,</span> <span class="s">"Swift"</span><span class="p">)</span>
<span class="kd">val</span> <span class="py">nullableList</span><span class="p">:</span> <span class="nc">List</span><span class="p">&lt;</span><span class="nc">String</span><span class="p">?&gt;</span> <span class="p">=</span> <span class="nf">listOf</span><span class="p">(</span><span class="s">"Kotlin"</span><span class="p">,</span> <span class="k">null</span><span class="p">,</span> <span class="s">"Swift"</span><span class="p">)</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>When working with nullable collections, you can use functions like filterNotNull to remove null values:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
</pre></td><td class="rouge-code"><pre><span class="nf">println</span><span class="p">(</span><span class="n">nullableList</span><span class="p">.</span><span class="nf">filterNotNull</span><span class="p">())</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>Which prints:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
</pre></td><td class="rouge-code"><pre>[Kotlin, Swift]
</pre></td></tr></tbody></table></code></pre></div></div>

<p>I encourage you to explore further Kotlin’s collections API as there are many more functions provided to make working with nulls easier.</p>

<h1 id="null-safety-in-functions">Null Safety in Functions</h1>
<p>Kotlin’s null safety extends to functions as well. You can define functions that accept nullable or non-nullable parameters and return 
nullable or non-nullable values. The type system enforces null safety at every step, preventing you from passing or returning null values 
where they are not expected.</p>

<h3 id="nullable-parameters">Nullable Parameters</h3>
<p>Here’s an example of a function with a nullable parameter:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
6
7
</pre></td><td class="rouge-code"><pre><span class="k">fun</span> <span class="nf">printLength</span><span class="p">(</span><span class="n">str</span><span class="p">:</span> <span class="nc">String</span><span class="p">?)</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">str</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span> <span class="p">{</span>
        <span class="nf">println</span><span class="p">(</span><span class="s">"Length: ${str.length}"</span><span class="p">)</span>
    <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
        <span class="nf">println</span><span class="p">(</span><span class="s">"String is null"</span><span class="p">)</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>The function <code class="language-plaintext highlighter-rouge">printLength</code> checks if the parameter str is null before attempting to access its length, ensuring that no NPE occurs.
Note that there’s no <code class="language-plaintext highlighter-rouge">?</code> after checking that value is not null. Kotlin “knows” by utilising smart casts (on that later) that <code class="language-plaintext highlighter-rouge">str</code> 
is not null and therefor treats it as such.</p>

<h3 id="nullable-return-types">Nullable Return Types</h3>
<p>You can also define functions that return nullable types:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
</pre></td><td class="rouge-code"><pre><span class="k">fun</span> <span class="nf">findString</span><span class="p">(</span><span class="n">strings</span><span class="p">:</span> <span class="nc">List</span><span class="p">&lt;</span><span class="nc">String</span><span class="p">&gt;,</span> <span class="n">query</span><span class="p">:</span> <span class="nc">String</span><span class="p">):</span> <span class="nc">String</span><span class="p">?</span> <span class="p">{</span>
    <span class="k">return</span> <span class="n">strings</span><span class="p">.</span><span class="nf">find</span> <span class="p">{</span> <span class="n">it</span> <span class="p">==</span> <span class="n">query</span> <span class="p">}</span>
<span class="p">}</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>In this example, the function <code class="language-plaintext highlighter-rouge">findString</code> returns a nullable String.</p>

<h1 id="related-null-safety-features">Related Null Safety Features</h1>

<p>Kotlin provides several related features to handle nullability more effectively, including smart casts, the let function, and the run function.</p>

<h3 id="smart-casts">Smart Casts</h3>
<p>Kotlin’s smart cast feature automatically casts a nullable type to a non-nullable type after a null check (as we noticed in previous example in nullable parameters section):</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
6
7
</pre></td><td class="rouge-code"><pre><span class="k">fun</span> <span class="nf">printLength</span><span class="p">(</span><span class="n">str</span><span class="p">:</span> <span class="nc">String</span><span class="p">?)</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">str</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span> <span class="p">{</span>
        <span class="nf">println</span><span class="p">(</span><span class="s">"Length: ${str.length}"</span><span class="p">)</span> <span class="c1">// str is automatically cast to non-nullable</span>
    <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
        <span class="nf">println</span><span class="p">(</span><span class="s">"String is null"</span><span class="p">)</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>Smart casts reduce the need for explicit casting and make the code more concise and readable.</p>

<h3 id="the-let-function">The let Function</h3>
<p>The <code class="language-plaintext highlighter-rouge">let</code> function belongs to scope functions and is a powerful tool for working with nullable values. It executes a block of code only if the value is not null:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
</pre></td><td class="rouge-code"><pre><span class="n">nullableString</span><span class="o">?.</span><span class="nf">let</span> <span class="p">{</span> <span class="nf">println</span><span class="p">(</span><span class="s">"Length: ${it.length}"</span><span class="p">)</span> <span class="p">}</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">let</code> function ensures that the block of code is only executed when <code class="language-plaintext highlighter-rouge">nullableString</code> is not null, providing a safe and idiomatic way to handle nullable values.</p>

<h3 id="the-run-function">The run Function</h3>
<p>The <code class="language-plaintext highlighter-rouge">run</code> function is similar to <code class="language-plaintext highlighter-rouge">let</code>, but it allows you to work with a nullable object and return a result:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
</pre></td><td class="rouge-code"><pre><span class="kd">val</span> <span class="py">lengthOrNull</span><span class="p">:</span> <span class="nc">Int</span><span class="p">?</span> <span class="p">=</span> <span class="n">nullableString</span><span class="o">?.</span><span class="nf">run</span> <span class="p">{</span> <span class="n">length</span> <span class="p">}</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>In this example, run executes the block of code if nullableString is not null and returns the result of the block. If nullableString is null, the result is null.</p>

<h1 id="conclusion">Conclusion</h1>
<p>Kotlin’s null safety is a powerful feature that helps developers write safer and more reliable code by eliminating the 
risk of null pointer exceptions. By distinguishing between nullable and non-nullable types, providing safe call operators, 
and offering advanced features like smart casts and the let function, Kotlin ensures that nullability is handled explicitly 
and correctly.</p>

<p>Understanding and leveraging these features will make your Kotlin code more robust, maintainable, and less prone to runtime exceptions. 
Embrace Kotlin’s null safety and experience the benefits of a language designed to minimize common pitfalls and improve code quality.</p>]]></content><author><name>Albert Latacz</name></author><category term="blog" /><category term="kotlin" /><category term="coding" /><category term="kotlin_fundamentals" /><summary type="html"><![CDATA[Learn how to handle nullable types effectively and avoid those dreaded NullPointerExceptions.]]></summary></entry><entry><title type="html">Exploring Kotlin Power-Assert</title><link href="https://www.albertlatacz.com/blog/kotlin-power-assert/" rel="alternate" type="text/html" title="Exploring Kotlin Power-Assert" /><published>2024-06-18T08:25:00+00:00</published><updated>2024-06-18T08:25:00+00:00</updated><id>https://www.albertlatacz.com/blog/kotlin-power-assert</id><content type="html" xml:base="https://www.albertlatacz.com/blog/kotlin-power-assert/"><![CDATA[<p>Kotlin, as a modern, expressive language, continues to push the boundaries of developer productivity and code quality. 
Among its latest features is the power-assert compiler plugin, an assertion plugin designed to improve the way we write and debug tests. 
<a href="https://github.com/bnorm/kotlin-power-assert">Originally developed by Brian Norman</a>, this plugin has recently been incorporated into Kotlin as an experimental feature.</p>

<p>In this blog post, we’ll scrape the surface of what Kotlin power-assert is, how it works, and why you might consider incorporating it into your development workflow.</p>

<h1 id="what-is-kotlin-power-assert">What is Kotlin Power-Assert?</h1>
<p>Kotlin power-assert is a compiler plugin that enhances assertion statements in your tests by providing detailed feedback when an assertion fails. 
Traditional assertions often leave developers with vague messages like “expected true but was false”, which can be frustrating and time-consuming to debug. 
Power-assert aims to solve this by offering more context and clarity.</p>

<h1 id="setting-up-power-assert">Setting Up Power-Assert</h1>
<p>To start using power-assert in your Kotlin project, you’ll need to enable the plugin.
Check out the official <a href="https://kotlinlang.org/docs/power-assert.html">Kotlin documentation on power-assert</a> which gives up-to-date detailed guide on how to set it up and use it.</p>

<h1 id="how-does-power-assert-work">How Does Power-Assert Work?</h1>
<p>When an assertion fails, power-assert provides a detailed visual representation of the failed expression. 
This includes the values of variables and the structure of the expression at the time of failure. 
By doing so, it helps developers quickly pinpoint the cause of the failure without needing to manually 
insert print statements or debug through the code.</p>

<p>For example, consider the following traditional assertion:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
</pre></td><td class="rouge-code"><pre><span class="nf">assert</span><span class="p">(</span><span class="n">a</span> <span class="p">*</span> <span class="n">b</span> <span class="p">==</span> <span class="n">c</span> <span class="p">+</span> <span class="n">d</span><span class="p">)</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>If this assertion fails, a standard error message might tell you that the expression is false, 
but it won’t provide much context. With power-assert, the error message will break down the expression 
and show the values of a, b, c, and d, helping you pinpoint the cause of the failure more quickly.</p>

<p>And so you will see:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
6
7
8
9
10
</pre></td><td class="rouge-code"><pre>Assertion failed
assert(a * b == c + d)
       | | | |  | | |
       | | | |  | | 1
       | | | |  | 11
       | | | |  10
       | | | false
       | | 1
       | 12
       12
</pre></td></tr></tbody></table></code></pre></div></div>

<p>This visualization clearly shows the values of a, b, c and d therefore making it immediately obvious why the assertion failed.</p>

<h1 id="asserting-on-complex-values">Asserting On Complex Values</h1>

<p>Consider the following data class and test</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="rouge-code"><pre><span class="kd">data class</span> <span class="nc">Person</span><span class="p">(</span>
    <span class="kd">val</span> <span class="py">firstName</span><span class="p">:</span> <span class="nc">String</span><span class="p">,</span>
    <span class="kd">val</span> <span class="py">lastName</span><span class="p">:</span> <span class="nc">String</span><span class="p">,</span>
    <span class="kd">val</span> <span class="py">age</span><span class="p">:</span> <span class="nc">Int</span>
<span class="p">)</span>

<span class="nd">@Test</span>
<span class="k">fun</span> <span class="nf">`power</span> <span class="n">assert</span> <span class="n">complex</span> <span class="nf">values`</span><span class="p">()</span> <span class="p">{</span>
    <span class="kd">val</span> <span class="py">charlie</span> <span class="p">=</span> <span class="nc">Person</span><span class="p">(</span><span class="s">"Charlie"</span><span class="p">,</span> <span class="s">"Brown"</span><span class="p">,</span> <span class="mi">23</span><span class="p">)</span>
    <span class="kd">val</span> <span class="py">sally</span> <span class="p">=</span> <span class="nc">Person</span><span class="p">(</span><span class="s">"Sally"</span><span class="p">,</span> <span class="s">"Gray"</span><span class="p">,</span> <span class="mi">21</span><span class="p">)</span>
    <span class="nf">assert</span><span class="p">(</span><span class="n">charlie</span><span class="p">.</span><span class="n">age</span> <span class="p">==</span> <span class="n">sally</span><span class="p">.</span><span class="n">age</span><span class="p">)</span>
<span class="p">}</span>
</pre></td></tr></tbody></table></code></pre></div></div>

<p>The plugin will show value for each of the objects and fields in the assertion, and will render the following:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
6
7
8
</pre></td><td class="rouge-code"><pre>Assertion failed
assert(charlie.age == sally.age)
       |       |   |  |     |
       |       |   |  |     21
       |       |   |  Person(firstName=Sally, lastName=Gray, age=21)
       |       |   false
       |       23
       Person(firstName=Charlie, lastName=Brown, age=23)
</pre></td></tr></tbody></table></code></pre></div></div>

<p>This output clearly shows how power-assert type of assertion can help with providing more context around tested expressions.</p>

<h1 id="deep-dive-resources">Deep-Dive Resources</h1>
<p>For a more comprehensive exploration of Kotlin’s power-assert have a look at the most recent talk from KotlinConf’24 by Brian Norman:</p>
<ul>
  <li><a href="https://www.youtube.com/watch?v=N8u-6d0iCiE">Kotlin + Power-Assert = ❤️</a></li>
</ul>

<p>Also Duncan McGregor’s videos offer invaluable insights:</p>
<ul>
  <li><a href="https://www.youtube.com/watch?v=ujxNvC_Q_cA">Kotlin Power Assert</a></li>
  <li><a href="https://www.youtube.com/watch?v=kqe7bVp_vYY">Should you use Kotlin Power Assert?</a></li>
</ul>

<p>These videos delve into practical examples, highlight some problems and considerations when using power-assert.</p>

<h1 id="conclusion">Conclusion</h1>
<p>Kotlin power-assert is an experimental yet promising feature that can significantly enhance the way we write and debug tests. 
By offering more informative and readable error messages, it helps developers quickly identify and fix issues. 
Although power-assert is not a new concept and has been implemented for several languages already (e.g. <a href="https://github.com/jkschneider/java-power-assert">Java</a>, <a href="https://github.com/erdos/erdos.assert">Clojure</a>, <a href="https://github.com/power-assert-js/power-assert">JS</a>, <a href="https://github.com/ToQoz/gopwt">Go</a>), 
it’s great to see it making it’s way into Kotlin.</p>

<p>As Kotlin continues to evolve, tools like power-assert demonstrate the JetBrains commitment to providing 
developers with the best possible tools and features. Whether you’re a seasoned Kotlin developer or 
just getting started, incorporating power-assert into your testing strategy is worth considering.</p>]]></content><author><name>Albert Latacz</name></author><category term="blog" /><category term="kotlin" /><category term="coding" /><category term="testing" /><summary type="html"><![CDATA[Discover the new Kotlin power-assert compiler plugin and how it can improve your testing and debugging experience.]]></summary></entry></feed>