Jekyll2023-06-25T22:28:01+00:00https://michael.codes/feed.xmlMichael.codesMichael BaldwinInstalling nodejs on macOS Apple Silicon (M1)2021-01-19T01:16:12+00:002021-01-19T01:16:12+00:00https://michael.codes/posts/nodejs_apple_silicon<p>I recently bought a new MacBook Pro with the M1 Apple Silicon CPU. While most things seem to be working great, some developer tools are not yet distributed as native aarch64 binaries. Currently, nodejs is one of those tools. The developers are working on <a href="https://github.com/nodejs/build/issues/2474">official support</a>, but it isn’t available yet. Fortunately thanks to the <a href="https://github.com/nvm-sh/nvm">nvm</a> project it is still easy to get up and running.</p>
<p>First, if you do not already have the xcode command line tools installed you should install them. This will download the needed C++ compiler and other development tools. Do this by running:</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>xcode-select <span class="nt">--install</span>
</code></pre></div></div>
<p>Once that completes, install nvm per their instructions. The command will look something like the following (to ensure you get the latest version of nvm use the command from <a href="https://github.com/nvm-sh/nvm#install--update-script">Github</a>).</p>
<p>Note that if you do not already have a profile file (~/.bash_profile, ~/.zshrc, ~/.profile, or ~/.bashrc) for your shell it won’t be able to install correctly. You should create the appropriate file(s) first before running the command below.</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>curl <span class="nt">-o-</span> https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh | bash
</code></pre></div></div>
<p>Now that you have nvm installed you can run the following command to install node. Version 15 is the one that currently (Jan 2021) works on aarch64 for Mac.</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>nvm <span class="nb">install </span>v15
</code></pre></div></div>
<p>If everything works correctly this step will take a while to compile everything and copy the newly buily node to the correct install location inside the <code class="language-plaintext highlighter-rouge">~/.nvm</code> directory. After the build and install completes test the install by running:</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>node <span class="nt">--version</span>
</code></pre></div></div>
<p>You will probably need to close and re-open your terminal for the command to be found.</p>
<p>Finally, you will want to clear the nvm cache to reduce clutter. After the build mine was consuming about 11GB, vs about 100MB once the cache was cleared. This can be done using:</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>nvm cache clear
</code></pre></div></div>
<p>Hopefully, this helps someone else that is also on the bleeding edge of Apple hardware!</p>
<p><small>This article is also published on <a href="https://dev.to/mkbaldwin/installing-nodejs-on-macos-apple-silicon-m1-22a4">dev.to</a>.</small></p>Michael BaldwinI recently bought a new MacBook Pro with the M1 Apple Silicon CPU. While most things seem to be working great, some developer tools are not yet distributed as native aarch64 binaries. Currently, nodejs is one of those tools. The developers are working on official support, but it isn’t available yet. Fortunately thanks to the nvm project it is still easy to get up and running.Display latest blog posts on GitHub profile readme2020-07-19T20:02:01+00:002020-07-19T20:02:01+00:00https://michael.codes/posts/github-profile-readme<p>Recently GitHub updated the user profile page to allow custom user-defined content to be displayed. This is done via
a profile README.</p>
<p><img src="https://michael.codes/images/blog/2020/07/19/0_github_profile.png" alt="GitHub Profile" class="align-center" /></p>
<p>Adding your profile readme section is quite simple. To start, create a new repository with your GitHub username
<code class="language-plaintext highlighter-rouge">YourGithubUsername/YourGithubUsername</code> and initialize it with a <code class="language-plaintext highlighter-rouge">README.md</code> file. Note that the repository must be
public. When you create the repository GitHub will display a message telling you that it is a ‘special’ repository.</p>
<p><img src="https://michael.codes/images/blog/2020/07/19/1_repo_create.png" alt="Creating a repository" class="align-center" /></p>
<p>Any static content you define and commit into the README in this repository will be displayed on your profile.</p>
<h3 id="displaying-blog-post-links">Displaying blog post links</h3>
<p>The GitHub profile readme section only supports static content, but it would be nice to display more dynamic information
on a profile. In my case, I wanted to be able to put links to my latest blog posts. To achieve this I am going to use
GitHub Actions.</p>
<p>My blog (built with Jekyll) has an Atom feed listing all of my posts. To update the content in my readme I will create
an action to fetch the feed and parse out the five latest posts. Since Atom is XML I used a simple XSLT to transform
the XML into Markdown. Create the XSLT file below and commit to your profile readme repository as<br />
<code class="language-plaintext highlighter-rouge">scripts/recent-posts.xslt</code>.</p>
<p><em>Note: If your blog does not use an Atom feed you will need to update this XSLT for the file format you have available.</em></p>
<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp"><?xml version="1.0"?></span>
<span class="nt"><xsl:stylesheet</span> <span class="na">version=</span><span class="s">"1.0"</span> <span class="na">xmlns:xsl=</span><span class="s">"http://www.w3.org/1999/XSL/Transform"</span>
<span class="na">xmlns:at=</span><span class="s">"http://www.w3.org/2005/Atom"</span><span class="nt">></span>
<span class="nt"><xsl:output</span> <span class="na">method=</span><span class="s">"text"</span><span class="nt">/></span>
<span class="nt"><xsl:strip-space</span> <span class="na">elements=</span><span class="s">"*"</span><span class="nt">/></span>
<span class="nt"><xsl:template</span> <span class="na">match=</span><span class="s">"/at:feed"</span><span class="nt">></span>
<span class="nt"><xsl:text></span>### Recent Blog Posts<span class="nt"></xsl:text></span>
<span class="nt"><xsl:text></span><span class="ni">&#xa;&#xa;</span><span class="nt"></xsl:text></span>
<span class="nt"><xsl:apply-templates/></span>
<span class="nt"></xsl:template></span>
<span class="c"><!-- Only display the first 5 posts from the list --></span>
<span class="nt"><xsl:template</span> <span class="na">match=</span><span class="s">"at:entry[position() &lt; 6]"</span><span class="nt">></span>
<span class="nt"><xsl:value-of</span> <span class="na">select=</span><span class="s">"concat(' * [', at:link/@title, '](', at:link/@href, ')')"</span><span class="nt">/></span>
<span class="nt"><xsl:text></span><span class="ni">&#xa;</span><span class="nt"></xsl:text></span>
<span class="nt"></xsl:template></span>
<span class="nt"><xsl:template</span> <span class="na">match=</span><span class="s">"text()"</span><span class="nt">/></span>
<span class="nt"></xsl:stylesheet></span>
</code></pre></div></div>
<p>To create static content in the readme as well we will create a static markdown file named <code class="language-plaintext highlighter-rouge">README_START.md</code>. In this
file you can put any content you want to be shown before the latest posts list.</p>
<p>Commit these files and push them to GitHub. Now we have the initial content we will create a GitHub action to<br />
update our readme automatically. Under your profile repository click on the <code class="language-plaintext highlighter-rouge">Actions</code> tab and then <code class="language-plaintext highlighter-rouge">New workflow</code>.<br />
Select a simple workflow as a starter. GitHub will now give you a starter script, that you can either edit or replace
using the script below as a basis. Also, note that you will want to rename the script from the default <code class="language-plaintext highlighter-rouge">blank.yml</code>.</p>
<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># This is a basic workflow to help you get started with Actions</span>
<span class="na">name</span><span class="pi">:</span> <span class="s">Update Latest Posts</span>
<span class="c1"># Controls when the action will run. Triggers the workflow on push or pull request</span>
<span class="c1"># events but only for the master branch</span>
<span class="na">on</span><span class="pi">:</span>
<span class="na">workflow_dispatch</span><span class="pi">:</span>
<span class="na">schedule</span><span class="pi">:</span>
<span class="c1"># Cron syntax, run at 00:00 UTC daily</span>
<span class="pi">-</span> <span class="na">cron</span><span class="pi">:</span> <span class="s2">"</span><span class="s">0</span><span class="nv"> </span><span class="s">0</span><span class="nv"> </span><span class="s">*</span><span class="nv"> </span><span class="s">*</span><span class="nv"> </span><span class="s">*"</span>
<span class="c1"># A workflow run is made up of one or more jobs that can run sequentially or in parallel</span>
<span class="na">jobs</span><span class="pi">:</span>
<span class="c1"># This workflow contains a single job called "build"</span>
<span class="na">build</span><span class="pi">:</span>
<span class="c1"># The type of runner that the job will run on</span>
<span class="na">runs-on</span><span class="pi">:</span> <span class="s">ubuntu-latest</span>
<span class="c1"># Steps represent a sequence of tasks that will be executed as part of the job</span>
<span class="na">steps</span><span class="pi">:</span>
<span class="c1"># Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it</span>
<span class="pi">-</span> <span class="na">uses</span><span class="pi">:</span> <span class="s">actions/checkout@v2</span>
<span class="c1"># Perform the steps needed</span>
<span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">Pull Latest Repo Content</span>
<span class="na">run</span><span class="pi">:</span> <span class="s">git pull</span>
<span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">Download Saxon-HE</span>
<span class="na">run</span><span class="pi">:</span> <span class="s">curl https://repo1.maven.org/maven2/net/sf/saxon/Saxon-HE/9.9.1-7/Saxon-HE-9.9.1-7.jar > saxon.jar</span>
<span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">Fetch website Atom Feed</span>
<span class="na">run</span><span class="pi">:</span> <span class="s">curl https://michael.codes/feed.xml > feed.xml</span>
<span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">Perform XSL Transformation</span>
<span class="na">run</span><span class="pi">:</span> <span class="s">java -cp ./saxon.jar net.sf.saxon.Transform -s:feed.xml -xsl:$GITHUB_WORKSPACE/scripts/recent-posts.xslt -o:README_END.md</span>
<span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">Combine Files</span>
<span class="na">run</span><span class="pi">:</span> <span class="s">cat $GITHUB_WORKSPACE/README_START.md README_END.md > $GITHUB_WORKSPACE/README.md</span>
<span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">Commit Changes</span>
<span class="na">run</span><span class="pi">:</span> <span class="pi">|</span>
<span class="s">git add README.md</span>
<span class="s">git diff</span>
<span class="s">git config --global user.email "github-action-bot@example.com"</span>
<span class="s">git config --global user.name "GitHub Action Bot"</span>
<span class="s">git commit -m "Updated README" -a || echo "No changes to commit"</span>
<span class="s">git push</span>
</code></pre></div></div>
<p>The script above does the following:</p>
<ul>
<li>Schedules the action to run once a day (or it can be run manually from within GitHub.</li>
<li>Ensures the latest content from the GitHub profile repository is checked out.</li>
<li>Downloads both SaxonHE (our XSLT processor). The <code class="language-plaintext highlighter-rouge">ubuntu-latest</code> image includes Java that can easily be used to
run XSLTs.</li>
<li>Downloads the latest Atom feed from my website.</li>
<li>Runs a transformation that generates a <code class="language-plaintext highlighter-rouge">README_END.md</code> file.</li>
<li>Combines the readme start and end files into a single <code class="language-plaintext highlighter-rouge">README.md</code> file that GitHub will display.</li>
<li>Ensures our changes are committed.</li>
</ul>
<p><em>Before committing the script make sure to update to for your site.</em></p>
<p>Now, you can run the action and see that it successfully generates the <code class="language-plaintext highlighter-rouge">README.md</code> file and commits it into the
repository.</p>
<p><small>This article is also published on <a href="https://dev.to/mkbaldwin/display-latest-blog-posts-on-github-profile-readme-cba">dev.to</a>.</small></p>Michael BaldwinRecently GitHub updated the user profile page to allow custom user-defined content to be displayed. This is done via a profile README.Kotlin Type Aliases2020-06-27T19:01:09+00:002020-06-27T19:01:09+00:00https://michael.codes/posts/kotlin-typealias<p>Something I recently learned about in Kotlin, that I do not see talked about very often, are
type aliases. Type aliases allow for custom names to be specified for existing types.
This is convenient for long or complex types.</p>
<p>These are particularly useful for function types that have particularly complex syntax.
For example if we have a function that takes a handler function as a parameter.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">fun</span> <span class="nf">handleEvent</span><span class="p">(</span><span class="n">handler</span><span class="p">:</span> <span class="p">(</span><span class="n">type</span><span class="p">:</span> <span class="nc">EventType</span><span class="p">,</span> <span class="n">message</span><span class="p">:</span> <span class="nc">String</span><span class="p">)</span> <span class="p">-></span> <span class="nc">Unit</span><span class="p">)</span> <span class="p">{</span>
<span class="c1">// Some logic...</span>
<span class="p">}</span>
</code></pre></div></div>
<p>We can use a type alias to make a bit more readable by defining a name to the function type.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">typealias</span> <span class="nc">EventHandler</span> <span class="p">=</span> <span class="p">(</span><span class="nc">EventType</span><span class="p">,</span> <span class="nc">String</span><span class="p">)</span> <span class="p">-></span> <span class="nc">Unit</span>
<span class="k">fun</span> <span class="nf">handleEvent</span><span class="p">(</span><span class="n">handler</span><span class="p">:</span> <span class="nc">EventHandler</span><span class="p">)</span> <span class="p">{</span>
<span class="c1">// Some logic...</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Note that type aliases are not creating new types. Behind the scenes the Kotlin compiler
takes the custom name and replaces it with the actual type. This means you can work with
the original type and the alias interchangeably.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">typealias</span> <span class="nc">CharacterString</span> <span class="p">=</span> <span class="nc">String</span>
<span class="k">fun</span> <span class="nf">pl</span><span class="p">(</span><span class="n">s</span><span class="p">:</span> <span class="nc">CharacterString</span><span class="p">)</span> <span class="p">=</span> <span class="nf">println</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="k">fun</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>
<span class="kd">val</span> <span class="py">test1</span><span class="p">:</span> <span class="nc">CharacterString</span> <span class="p">=</span> <span class="s">"Test String"</span>
<span class="kd">val</span> <span class="py">test2</span><span class="p">:</span> <span class="nc">String</span> <span class="p">=</span> <span class="s">"Test String 2"</span>
<span class="nf">pl</span><span class="p">(</span><span class="n">test1</span><span class="p">)</span>
<span class="nf">pl</span><span class="p">(</span><span class="n">test2</span><span class="p">)</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Obviously, overusing this feature could result in less readable code, but used appropriately
can be very useful. For more details see the
<a href="https://kotlinlang.org/docs/reference/type-aliases.html">Type Aliases</a> section
of the Kotlin documentation.</p>
<p><small>This article is also published on <a href="https://dev.to/mkbaldwin/kotlin-type-aliases-4g0f">dev.to</a>.</small></p>Michael BaldwinSomething I recently learned about in Kotlin, that I do not see talked about very often, are type aliases. Type aliases allow for custom names to be specified for existing types. This is convenient for long or complex types.Introduction to Kotlin (Part 3): classes, properties, objects, and interfaces2020-06-12T14:03:24+00:002020-06-12T14:03:24+00:00https://michael.codes/posts/kotlin-part3-classes<p>In <a href="https://michael.codes/posts/kotlin-part1-variables-types-functions">part one</a> of this series we talked about
variables, types, and functions, and in <a href="https://michael.codes/posts/kotlin-part2-conditionals-loops">part two</a>
we covered conditionals and looping. In part three we will now talk about classes in Kotlin.</p>
<h3 id="class-basics">Class basics</h3>
<p>Declared with the <code class="language-plaintext highlighter-rouge">class</code> keyword. If the class has no body then curly braces can be omitted.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">Book</span> <span class="p">{}</span>
</code></pre></div></div>
<p>A class can have one primary constructor and any number of secondary constructors. In Kotlin the primary constructor is
declared directly in the class definition.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">Book</span><span class="p">(</span><span class="n">title</span><span class="p">:</span> <span class="nc">String</span><span class="p">)</span>
</code></pre></div></div>
<p>Notice that in Kotlin the default constructor doesn’t contain any initialization code. Initialization code is placed
into <code class="language-plaintext highlighter-rouge">init</code> blocks. These blocks will be executed when the class is being initialized after instantiation. Any
parameters specified in the primary constructor can be accessed within the initializer block or when declaring properties.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">Book</span><span class="p">(</span><span class="n">title</span><span class="p">:</span> <span class="nc">String</span><span class="p">,</span> <span class="n">author</span><span class="p">:</span> <span class="nc">String</span><span class="p">)</span> <span class="p">{</span>
<span class="k">private</span> <span class="kd">val</span> <span class="py">title</span> <span class="p">=</span> <span class="n">title</span>
<span class="k">private</span> <span class="kd">val</span> <span class="py">author</span><span class="p">:</span> <span class="nc">String</span>
<span class="nf">init</span> <span class="p">{</span>
<span class="nf">println</span><span class="p">(</span><span class="s">"Book initialized with title: $title and author: $author"</span><span class="p">)</span>
<span class="k">this</span><span class="p">.</span><span class="n">author</span> <span class="p">=</span> <span class="n">author</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Declaring properties and initializing them with a constructor is a very common pattern. So, Kotlin includes a shorter
syntax allowing the properties and initializing them directly in the constructor.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">Book</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="k">private</span> <span class="kd">val</span> <span class="py">author</span><span class="p">:</span> <span class="nc">String</span> <span class="p">=</span> <span class="s">"Anonymous"</span><span class="p">)</span>
</code></pre></div></div>
<p>These properties can be defined to be either <code class="language-plaintext highlighter-rouge">val</code> or <code class="language-plaintext highlighter-rouge">var</code> and can specify visibility modifiers such as <code class="language-plaintext highlighter-rouge">private</code>.
Much like in functions, parameters can also have default values specified.</p>
<p>Creating an instance of a class is done by calling the constructor like it is a function. Kotlin has no special
keywords used for instantiation.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">val</span> <span class="py">myBook</span> <span class="p">=</span> <span class="nc">Book</span><span class="p">(</span><span class="s">"Some Great Work"</span><span class="p">,</span> <span class="s">"A. Author"</span><span class="p">)</span>
</code></pre></div></div>
<p>Secondary constructors are created using the <code class="language-plaintext highlighter-rouge">constructor</code> keyword. Secondary constructors can call the default (or
other) constructor using the <code class="language-plaintext highlighter-rouge">this</code> keyword.</p>
<p>Multiple secondary constructors are allowed and may contain initialization logic.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">Book</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="kd">val</span> <span class="py">author</span><span class="p">:</span> <span class="nc">String</span><span class="p">)</span> <span class="p">{</span>
<span class="k">private</span> <span class="kd">var</span> <span class="py">price</span><span class="p">:</span> <span class="nc">Double</span> <span class="p">=</span> <span class="mf">0.0</span>
<span class="k">constructor</span><span class="p">(</span><span class="n">title</span><span class="p">:</span> <span class="nc">String</span><span class="p">):</span> <span class="k">this</span><span class="p">(</span><span class="n">title</span><span class="p">,</span> <span class="s">"Unknown"</span><span class="p">)</span>
<span class="k">constructor</span><span class="p">(</span><span class="n">title</span><span class="p">:</span> <span class="nc">String</span><span class="p">,</span> <span class="n">author</span><span class="p">:</span> <span class="nc">String</span><span class="p">,</span> <span class="n">price</span><span class="p">:</span> <span class="nc">Double</span><span class="p">):</span> <span class="k">this</span><span class="p">(</span><span class="n">title</span><span class="p">,</span> <span class="n">author</span><span class="p">)</span> <span class="p">{</span>
<span class="k">this</span><span class="p">.</span><span class="n">price</span> <span class="p">=</span> <span class="n">price</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<h3 id="properties">Properties</h3>
<p>Properties in Kotlin are variables defined at the class level using the <code class="language-plaintext highlighter-rouge">val</code> or <code class="language-plaintext highlighter-rouge">var</code> keywords. By default properties
are <code class="language-plaintext highlighter-rouge">public</code>, but other visibility modifiers (e.g. <code class="language-plaintext highlighter-rouge">private</code> or <code class="language-plaintext highlighter-rouge">protected</code>) can be specified.</p>
<p>For compatibility with Java and other JVM languages getter and setter functions are created automatically for each
property. When needed a custom getter or setter can be provided.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">Person</span> <span class="p">{</span>
<span class="kd">var</span> <span class="py">name</span><span class="p">:</span> <span class="nc">String</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">name</span>
<span class="k">set</span><span class="p">(</span><span class="n">value</span><span class="p">)</span> <span class="p">{</span>
<span class="c1">// Do some logic</span>
<span class="k">this</span><span class="p">.</span><span class="n">name</span> <span class="p">=</span> <span class="n">value</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Note in the previous example that we can either use the shorthand assignment syntax or a code block just like when
defining functions.</p>
<h3 id="inheritance">Inheritance</h3>
<p>All classes in Kotlin all automatically inherit from the <code class="language-plaintext highlighter-rouge">Any</code> class. This is similar to <code class="language-plaintext highlighter-rouge">Object</code> in Java. By default
all Kotlin classes are final and cannot be extended. To make a class available for extension the <code class="language-plaintext highlighter-rouge">open</code> keyword must
be used when declaring the class.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">open</span> <span class="kd">class</span> <span class="nc">Vehicle</span><span class="p">(</span><span class="kd">val</span> <span class="py">color</span><span class="p">:</span> <span class="nc">String</span><span class="p">)</span> <span class="p">{</span>
<span class="k">fun</span> <span class="nf">start</span><span class="p">()</span> <span class="p">{</span>
<span class="c1">// Some Implementation</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<p>When we want to create a class that extends another we specify the new class name, a colon (<code class="language-plaintext highlighter-rouge">:</code>), and then the new
class name. If the new class has a primary constructor then the constructor of the base class must be called.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">Car</span><span class="p">(</span><span class="n">color</span><span class="p">:</span> <span class="nc">String</span><span class="p">)</span> <span class="p">:</span> <span class="nc">Vehicle</span><span class="p">(</span><span class="n">color</span><span class="p">)</span> <span class="p">{</span>
<span class="k">fun</span> <span class="nf">drive</span><span class="p">()</span> <span class="p">{</span>
<span class="c1">// Some Implementation</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<p>If the new class doesn’t have a primary constructor then each secondary constructor must call the parent constructor
using the <code class="language-plaintext highlighter-rouge">super</code> keyword.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">constructor</span><span class="p">(</span><span class="n">color</span><span class="p">:</span> <span class="nc">String</span><span class="p">)</span> <span class="p">:</span> <span class="k">super</span><span class="p">(</span><span class="n">color</span><span class="p">)</span>
</code></pre></div></div>
<p>To override functions or properties the parent class must specify these items as being <code class="language-plaintext highlighter-rouge">open</code>, just like with the class itself.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">open</span> <span class="kd">class</span> <span class="nc">Vehicle</span> <span class="p">{</span>
<span class="k">open</span> <span class="kd">val</span> <span class="py">type</span><span class="p">:</span> <span class="nc">String</span> <span class="p">=</span> <span class="s">"Vehicle"</span>
<span class="k">open</span> <span class="k">fun</span> <span class="nf">start</span><span class="p">()</span> <span class="p">{</span>
<span class="c1">// Some Implementation</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<p>In the derived class the functions and properties must be marked with the <code class="language-plaintext highlighter-rouge">override</code> keyword.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">Car</span><span class="p">:</span> <span class="nc">Vehicle</span><span class="p">()</span> <span class="p">{</span>
<span class="k">override</span> <span class="kd">val</span> <span class="py">type</span><span class="p">:</span> <span class="nc">String</span> <span class="p">=</span> <span class="s">"Car"</span>
<span class="k">override</span> <span class="k">fun</span> <span class="nf">start</span><span class="p">()</span> <span class="p">{</span>
<span class="k">super</span><span class="p">.</span><span class="nf">start</span><span class="p">()</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<h3 id="interfaces">Interfaces</h3>
<p>Kotlin also supports interfaces that work similarly to those in Java. Interfaces are defined using the <code class="language-plaintext highlighter-rouge">interface</code> keyword.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">interface</span> <span class="nc">Loggable</span> <span class="p">{</span>
<span class="k">fun</span> <span class="nf">loggerName</span><span class="p">():</span> <span class="nc">String</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Classes can implement one or more interfaces.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">MyClass</span> <span class="p">:</span> <span class="nc">Loggable</span><span class="p">,</span> <span class="nc">Serializable</span> <span class="p">{</span>
<span class="k">override</span> <span class="k">fun</span> <span class="nf">loggerName</span><span class="p">():</span> <span class="nc">String</span> <span class="p">{</span>
<span class="c1">//Some Implementation</span>
<span class="p">}</span>
<span class="c1">// ...</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Interfaces can inherit from other interfaces using a similar syntax to classes.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">interface</span> <span class="nc">Parent</span> <span class="p">{</span>
<span class="k">fun</span> <span class="nf">x</span><span class="p">()</span>
<span class="p">}</span>
<span class="kd">interface</span> <span class="nc">Child</span> <span class="p">:</span> <span class="nc">Parent</span> <span class="p">{</span>
<span class="k">fun</span> <span class="nf">y</span><span class="p">()</span>
<span class="p">}</span>
</code></pre></div></div>
<h3 id="objects-singleton">Objects (Singleton)</h3>
<p>Kotlin has built-in support for singleton classes using the <code class="language-plaintext highlighter-rouge">object</code> keyword.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">object</span> <span class="nc">MySingleton</span> <span class="p">{</span>
<span class="c1">// Functions and properties...</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Objects can also be defined as companions to regular classes. This is done by declaring a <code class="language-plaintext highlighter-rouge">companion object</code> inside of the class.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><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="nf">foo</span><span class="p">()</span> <span class="p">{</span>
<span class="c1">// Some logic</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Methods and properties in the companion object are accessed using the name of the parent object. This looks similar to
how static functions are called in Java, but the companion objects are real objects. The companion objects can implement
interfaces, have properties, etc.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">MyClass</span><span class="p">.</span><span class="nf">foo</span><span class="p">()</span>
</code></pre></div></div>
<h3 id="data-classes">Data Classes</h3>
<p>There are many cases where objects are created just to hold data. In Java these classes would define some class-level
variables as well as getters and setters. These types of classes require a lot of boilerplate code.</p>
<p>Kotlin provides a special type of class just for this purpose. Data classes are created with the <code class="language-plaintext highlighter-rouge">data class</code> keywords.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><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>
</code></pre></div></div>
<p>The Kotlin compiler will automatically create a getter and setter for each property as well as the following functions:</p>
<ul>
<li><code class="language-plaintext highlighter-rouge">equals()</code></li>
<li><code class="language-plaintext highlighter-rouge">hashCode()</code></li>
<li><code class="language-plaintext highlighter-rouge">toString()</code></li>
<li><code class="language-plaintext highlighter-rouge">copy()</code></li>
</ul>
<h3 id="what-next">What Next?</h3>
<p>In this post I have tried to cover most of the important details of classes, properties, objects, interfaces, and data
classes. There are still a lot more specific details that I simply don’t have the time and space to cover. Fortunately
the <a href="https://kotlinlang.org/docs/reference/">Kotlin reference</a> documentation is excellent and covers all the
topics in great detail.</p>
<p><small>This article is also published on <a href="https://dev.to/mkbaldwin/introduction-to-kotlin-part-3-classes-properties-objects-and-interfaces-2bjf">dev.to</a>.</small></p>Michael BaldwinIn part one of this series we talked about variables, types, and functions, and in part two we covered conditionals and looping. In part three we will now talk about classes in Kotlin.Introduction to Kotlin (Part 2): if, when, and looping2020-05-25T16:32:42+00:002020-05-25T16:32:42+00:00https://michael.codes/posts/kotlin-part2-conditionals-loops<p>In <a href="https://michael.codes/posts/kotlin-part1-variables-types-functions">part one</a> of this Introduction to Kotlin series, we talked about what Kotlin is and about some of the basics of the language
(variables, types, and functions). If you are completely new to Kotlin, that article is probably a good read before starting this one.</p>
<h2 id="making-decisions-if-and-when">Making decisions (if and when)</h2>
<p>Like most other programming languages, Kotlin includes support for conditional logic with <code class="language-plaintext highlighter-rouge">if</code>/<code class="language-plaintext highlighter-rouge">else</code>. The basic structure is the same as in Java.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span><span class="p">(</span><span class="n">booleanExpression</span><span class="p">)</span> <span class="p">{</span>
<span class="nf">println</span><span class="p">(</span><span class="s">"I'm true!"</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">"I'm false!"</span><span class="p">)</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Unlike in Java, <code class="language-plaintext highlighter-rouge">if</code>/<code class="language-plaintext highlighter-rouge">else</code> blocks are expressions that can return a value. When used as an expression the last line of each block is returned as the value.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">val</span> <span class="py">result</span> <span class="p">=</span> <span class="k">if</span><span class="p">(</span><span class="n">booleanExpression</span><span class="p">)</span> <span class="p">{</span>
<span class="s">"I'm true!"</span>
<span class="p">}</span>
<span class="k">else</span> <span class="p">{</span>
<span class="s">"I'm false!"</span>
<span class="p">}</span>
<span class="nf">println</span><span class="p">(</span><span class="n">result</span><span class="p">)</span>
</code></pre></div></div>
<p>If the <code class="language-plaintext highlighter-rouge">if</code> and <code class="language-plaintext highlighter-rouge">else</code> blocks contain a single expression, then this code can be simplified further.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">val</span> <span class="py">result</span> <span class="p">=</span> <span class="k">if</span><span class="p">(</span><span class="n">booleanExpression</span><span class="p">)</span> <span class="s">"I'm true!"</span> <span class="k">else</span> <span class="s">"I'm false!"</span>
<span class="nf">println</span><span class="p">(</span><span class="n">result</span><span class="p">)</span>
</code></pre></div></div>
<p>This pattern is similar to the ternary (<code class="language-plaintext highlighter-rouge">? :</code>) operator in Java, which Kotlin does not have.</p>
<p>In addition to <code class="language-plaintext highlighter-rouge">if</code> Kotlin also has another conditional called <code class="language-plaintext highlighter-rouge">when</code>. The <code class="language-plaintext highlighter-rouge">when</code> expression is a powerful alternative, and is especially useful when doing many comparisons together.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">val</span> <span class="py">cost</span> <span class="p">=</span> <span class="mi">12</span>
<span class="kd">val</span> <span class="py">result</span> <span class="p">=</span> <span class="k">when</span> <span class="p">{</span>
<span class="n">cost</span> <span class="p"><</span> <span class="mi">5</span> <span class="p">-></span> <span class="s">"It is cheap!"</span>
<span class="n">cost</span> <span class="p">></span> <span class="mi">50</span> <span class="p">-></span> <span class="s">"It is expensive!"</span>
<span class="k">else</span> <span class="p">-></span> <span class="s">"It's in between."</span>
<span class="p">}</span>
<span class="nf">println</span><span class="p">(</span><span class="n">result</span><span class="p">)</span>
</code></pre></div></div>
<p>When multiple conditional branches are required the <code class="language-plaintext highlighter-rouge">when</code> expression results in a much more concise code. The <code class="language-plaintext highlighter-rouge">when</code> expression requires that all possible branches must be covered. So, in this case, we must have an <code class="language-plaintext highlighter-rouge">else</code> branch. When using enumerations an else can be omitted when all values are covered by an existing branch.</p>
<p>If all conditional branches are going to be comparisons with a single value we can pass that as an argument to the <code class="language-plaintext highlighter-rouge">when</code> expression.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">val</span> <span class="py">count</span> <span class="p">=</span> <span class="mi">5</span>
<span class="n">result</span> <span class="p">=</span> <span class="k">when</span> <span class="p">(</span><span class="n">count</span><span class="p">)</span> <span class="p">{</span>
<span class="mi">1</span> <span class="p">-></span> <span class="s">"Only one!"</span>
<span class="mi">2</span><span class="p">,</span><span class="mi">3</span> <span class="p">-></span> <span class="s">"Two or three!"</span>
<span class="k">in</span> <span class="mi">4</span><span class="o">..</span><span class="mi">6</span> <span class="p">-></span> <span class="s">"Four to six!"</span>
<span class="k">else</span> <span class="p">-></span> <span class="s">"Seven or more!!"</span>
<span class="p">}</span>
<span class="nf">println</span><span class="p">(</span><span class="n">result</span><span class="p">)</span>
</code></pre></div></div>
<p>For this type of <code class="language-plaintext highlighter-rouge">when</code> expression we can either specify a single value, a comma-separated list of values, or a range using the <code class="language-plaintext highlighter-rouge">in</code> keyword. Once again we still must have an <code class="language-plaintext highlighter-rouge">else</code> statement to catch any non-matching values.</p>
<p>In this form, the <code class="language-plaintext highlighter-rouge">when</code> expression looks very similar to the switch statement in Java, only with more power and simpler syntax.</p>
<h2 id="looping">Looping</h2>
<p>The <code class="language-plaintext highlighter-rouge">for</code> loop in Kotlin allows for iterating over any object that provides an iterator, or over ranges. The <code class="language-plaintext highlighter-rouge">in</code> keyword The type on the variable defined in the loop can, in most cases, be omitted.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">for</span><span class="p">(</span><span class="n">item</span><span class="p">:</span> <span class="nc">Int</span> <span class="k">in</span> <span class="n">someCollection</span><span class="p">)</span> <span class="p">{</span>
<span class="nf">println</span><span class="p">(</span><span class="n">item</span><span class="p">)</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Kotlin does not utilize the C style for loop for iterating over a range of numbers. Instead, iteration is specified using <a href="https://kotlinlang.org/docs/reference/ranges.html">Range Expressions</a>. Ranges are created using the <code class="language-plaintext highlighter-rouge">..</code> operator (which is associated with the <code class="language-plaintext highlighter-rouge">rangeTo()</code> function).</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">for</span><span class="p">(</span><span class="n">i</span> <span class="k">in</span> <span class="mi">1</span><span class="o">..</span><span class="mi">5</span><span class="p">)</span> <span class="p">{</span>
<span class="nf">print</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
<span class="p">}</span>
<span class="c1">// Prints: 1, 2, 3, 4, and 5</span>
</code></pre></div></div>
<p>By default iterating over a range will increment the value by one each time. In some cases, you may want to increment by other values. This can be achieved by specifying <code class="language-plaintext highlighter-rouge">step</code> and a number. In the example below, the number will be increased by two each time until the ending value is reached.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">for</span><span class="p">(</span><span class="n">i</span> <span class="k">in</span> <span class="mi">1</span><span class="o">..</span><span class="mi">10</span> <span class="n">step</span> <span class="mi">2</span><span class="p">)</span> <span class="p">{</span>
<span class="nf">print</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
<span class="p">}</span>
<span class="c1">// Prints: 1, 3, 5, 7, and 9</span>
</code></pre></div></div>
<p>If you want the range to go in reverse order you can use <code class="language-plaintext highlighter-rouge">downTo</code> instead of <code class="language-plaintext highlighter-rouge">..</code>. This will result in the starting number being decremented by one (or another value when <code class="language-plaintext highlighter-rouge">step</code> is specified) until the ending value is reached.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">for</span><span class="p">(</span><span class="n">i</span> <span class="k">in</span> <span class="mi">5</span> <span class="n">downTo</span> <span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
<span class="nf">println</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
<span class="p">}</span>
<span class="c1">// Prints: 5, 4, 3, 2, and 1</span>
</code></pre></div></div>
<p>Kotlin also support <code class="language-plaintext highlighter-rouge">while</code> and <code class="language-plaintext highlighter-rouge">do while</code> loops. These loops work just as you would expect them to in Java.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">while</span><span class="p">(</span><span class="n">booleanExpression</span><span class="p">)</span> <span class="p">{</span>
<span class="c1">// ...</span>
<span class="p">}</span>
<span class="k">do</span> <span class="p">{</span>
<span class="c1">// ...</span>
<span class="p">}</span>
<span class="k">while</span><span class="p">(</span><span class="n">booleanExpression</span><span class="p">)</span>
</code></pre></div></div>
<h2 id="what-next">What next?</h2>
<p>In <a href="https://michael.codes/posts/kotlin-part3-classes">part three</a> of this series, we will talk about Kotlin classes.
Also, the <a href="https://kotlinlang.org/docs/reference">Kotlin Reference</a> documentation covers all of these items
discussed in this post in much more detail.</p>
<p><small>This article is also published on <a href="https://dev.to/mkbaldwin/introduction-to-kotlin-part-2-if-when-and-looping-4h56">dev.to</a>.</small></p>Michael BaldwinIn part one of this Introduction to Kotlin series, we talked about what Kotlin is and about some of the basics of the language (variables, types, and functions). If you are completely new to Kotlin, that article is probably a good read before starting this one.Introduction to Kotlin (Part 1): Variables, types, and functions2019-05-19T03:37:00+00:002019-05-19T03:37:00+00:00https://michael.codes/posts/kotlin-part1-variables-types-functions<h2 id="what-is-kotlin">What is Kotlin?</h2>
<p>If you are reading this then chances are you have already heard of <a href="https://kotlinlang.org">Kotlin</a>, but you may be
wondering what it is and why you should be interested. Kotlin is a modern cross-platform programming language developed
and backed by JetBrains. In 2017 Google announced Kotlin as a preferred language for Android development.</p>
<p>Kotlin code can be compiled for the Java Virtual Machine (JVM), JavaScript, or Native. All of the language concepts
discussed in this article should be common to all three platforms, but the primary focus is on JVM support and,
comparisons to Java will be made.</p>
<p>The Kotlin language was designed from the beginning with Java compatibility in mind. Code written in Kotlin is 100%
interoperable with Java. This means you can easily incorporate Kotlin into existing Java projects and/or take advantage
of the robust ecosystem of Java libraries and tools.</p>
<p><img src="https://michael.codes/images/blog/2020/05/18/java_kotlin_heart.png" alt="Java + Kotlin = Heart" class="align-center" /></p>
<p>Note, this article assumes that the reader already has some programming knowledge.</p>
<h2 id="variables-and-types">Variables and Types</h2>
<p>Variables are declared using the <code class="language-plaintext highlighter-rouge">var</code> keyword, or the <code class="language-plaintext highlighter-rouge">val</code> keyword for variables that are immutable (read-only). The
use of the immutable <code class="language-plaintext highlighter-rouge">val</code> should be preferred.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="py">mutableVariable</span><span class="p">:</span> <span class="nc">String</span> <span class="p">=</span> <span class="s">"Default Value"</span>
<span class="kd">val</span> <span class="py">immutableVariable</span><span class="p">:</span> <span class="nc">String</span> <span class="p">=</span> <span class="s">"The Value"</span>
</code></pre></div></div>
<p>Kotlin supports type inference during variable assignment. In other words, in some cases, the compiler can figure out
the type of the variable by context. So, the code shown before can be simplified to exclude the type definition.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="py">mutableVariable</span> <span class="p">=</span> <span class="s">"Default Value"</span>
<span class="kd">val</span> <span class="py">immutableVariable</span> <span class="p">=</span> <span class="s">"The Value"</span>
</code></pre></div></div>
<p>Kotlin includes very strong compile-time type checking and null-safety. By default, all variables are not nullable. If
you want a variable to allow null values it must be specified as a part of the type by adding a <code class="language-plaintext highlighter-rouge">?</code>.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="py">nullableVariable</span><span class="p">:</span> <span class="nc">Int</span><span class="p">?</span> <span class="p">=</span> <span class="k">null</span>
</code></pre></div></div>
<p>Because nullability of variables is explicitly defined, the Kotlin compiler can generate errors when code called is
unsafe and needs a null check. While the Kotlin type system is designed to try to prevent <code class="language-plaintext highlighter-rouge">NullPointerExceptions</code>, it
is still possible to have them under <a href="https://kotlinlang.org/docs/reference/null-safety.html">certain scenarios</a>.</p>
<p>Unlike Java, all of the basic types in Kotlin treated as objects. Basic types for String, Int, Long, Float, Double,
etc. are provided. Note that while these types are treated as objects in Kotlin code the compiler may represent them
as the appropriate JVM primitive once compiled.</p>
<h2 id="functions">Functions</h2>
<p>Functions in Kotlin are defined using the <code class="language-plaintext highlighter-rouge">fun</code> keyword.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">fun</span> <span class="nf">add</span><span class="p">(</span><span class="n">a</span><span class="p">:</span> <span class="nc">Int</span><span class="p">,</span> <span class="n">b</span><span class="p">:</span> <span class="nc">Int</span><span class="p">):</span> <span class="nc">Int</span> <span class="p">{</span>
<span class="k">return</span> <span class="n">a</span> <span class="p">+</span> <span class="n">b</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Notice in the example function that the declaration of parameters looks a lot like in variable declaration. When
declaring parameters the <code class="language-plaintext highlighter-rouge">var</code>/<code class="language-plaintext highlighter-rouge">val</code> keywords are omitted. Function parameters are always immutable.</p>
<p>The return type follows the function parameters. If a function returns no value then the <code class="language-plaintext highlighter-rouge">Unit</code> type is returned. In
this case, the return type can be omitted.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">fun</span> <span class="nf">sayHello</span><span class="p">(</span><span class="n">name</span><span class="p">:</span> <span class="nc">String</span><span class="p">)</span> <span class="p">{</span>
<span class="nf">println</span><span class="p">(</span><span class="s">"Hello $name!"</span><span class="p">)</span>
<span class="p">}</span>
</code></pre></div></div>
<p>In this example function, you will notice an additional handy feature in Kotlin, string interpolation. In our example,
the <code class="language-plaintext highlighter-rouge">$name</code> is replaced with the value in the parameter. So, the string <code class="language-plaintext highlighter-rouge">"Hello $name!"</code> is the equivalent of doing
<code class="language-plaintext highlighter-rouge">"Hello " + name + "!"</code> in Java code.</p>
<p>Many of the language features in Kotlin are designed to make code more concise and easier to read and write. If a
function is only a single expression that returns a value we can shorten the code and write a single-expression function.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">fun</span> <span class="nf">add</span><span class="p">(</span><span class="n">a</span><span class="p">:</span> <span class="nc">Int</span><span class="p">,</span> <span class="n">b</span><span class="p">:</span> <span class="nc">Int</span><span class="p">)</span> <span class="p">=</span> <span class="n">a</span> <span class="p">+</span> <span class="n">b</span>
</code></pre></div></div>
<p>A single-expression function allows us to further reduce the code written by omitting the type and allowing the
compiler to infer it from the expression.</p>
<p>Function parameters can be given default values and calling code can omit the argument. This is done directly in the
function definition by assigning a value to any of the parameters.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">fun</span> <span class="nf">message</span><span class="p">(</span><span class="n">message</span><span class="p">:</span> <span class="nc">String</span> <span class="p">=</span> <span class="s">"Hello"</span><span class="p">,</span> <span class="n">name</span><span class="p">:</span> <span class="s">"World"</span><span class="p">){</span>
<span class="nf">println</span><span class="p">(</span><span class="s">"$message $name!)
</span><span class="p">}</span>
</code></pre></div></div>
<p>A default value can be provided for any of the parameters. In the <code class="language-plaintext highlighter-rouge">message</code> function if you want to only override the
default value for <code class="language-plaintext highlighter-rouge">name</code> then a named parameter must be used. This is done by including the parameter name and assigning
a value in the function call. The example code below shows multiple ways this function can be called.</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">message</span><span class="p">(</span><span class="n">name</span> <span class="p">=</span> <span class="s">"Reader"</span><span class="p">)</span> <span class="c1">// Prints "Hello Reader!"</span>
<span class="nf">message</span><span class="p">(</span><span class="s">"Hey"</span><span class="p">,</span> <span class="s">"Reader"</span><span class="p">)</span> <span class="c1">// Prints "Hey Reader!"</span>
<span class="nf">message</span><span class="p">(</span><span class="s">"Hey"</span><span class="p">)</span> <span class="c1">// Prints "Hey World!"</span>
<span class="nf">message</span><span class="p">()</span> <span class="c1">// Prints "Hello World!"</span>
</code></pre></div></div>
<h2 id="what-next">What next?</h2>
<p>In <a href="https://michael.codes/posts/kotlin-part2-conditionals-loops">part two</a> of this series, we will talk about Kotlin conditionals and looping.
Also, the <a href="https://kotlinlang.org/docs/reference">Kotlin Reference</a> documentation covers all of these items
discussed in this post in much more detail.</p>
<p><small>This article is also published on <a href="https://dev.to/mkbaldwin/introduction-to-kotlin-part-1-variables-types-and-functions-193k">dev.to</a>.</small></p>Michael BaldwinWhat is Kotlin?Micronaut: A five-minute introduction2018-07-31T01:40:00+00:002018-07-31T01:40:00+00:00https://michael.codes/posts/micronaut-intro<p><a href="http://micronaut.io">Micronaut</a> is a new open source Java/JVM framework for creating microservice applications.
Development is being led by the creators of the Grails framework and is backed by
<a href="https://objectcomputing.com/products/micronaut">Object Computing</a>. The project is actively working toward its
official 1.0 release.</p>
<p>I’ve used Grails in the past for some personal projects and currently work primarily in the JVM ecosystem
professionally. So, when I saw the announcement about Micronaut, I decided to give it a try and see
what it was all about.</p>
<p>Micronaut’s goals are to provide fast startup times and small memory footprint. Both of which are important for deploying
microservices.</p>
<h2 id="getting-started">Getting Started</h2>
<p>To get started building an application, the <a href="https://docs.micronaut.io/snapshot/guide/index.html#quickStart">user guide</a>
recommends installing the Micronaut CLI. After completing the installation, you can create a new project with the following command.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>mn create-app my-app-name
</code></pre></div></div>
<p>By default, this creates a Gradle script to build a Java application using Micronaut. You can alternatively specify
maven as your build script, and either Java, Groovy, or Kotlin as a programming language. For my examples, I opted to use Groovy.
As you look at the generated project structure it will feel very familiar if you have worked with Spring framework before.</p>
<p>To start the application, just run:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>./gradlew run
</code></pre></div></div>
<p>You can also compile the application and run the main method in the <code class="language-plaintext highlighter-rouge">Application</code> class directly using your IDE.</p>
<h2 id="controllers">Controllers</h2>
<p>Much like in Spring Framework controllers are defined declaratively using the <code class="language-plaintext highlighter-rouge">@Controller</code> annotation.
Classes that are annotated with <code class="language-plaintext highlighter-rouge">@Controller</code> or other annotations are automatically detected.
Unlike other frameworks, like Spring, that rely on run-time classpath scanning this is done at compile time.</p>
<p>A simple controller looks as follows:</p>
<div class="language-groovy highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">io.micronaut.http.annotation.Controller</span>
<span class="kn">import</span> <span class="nn">io.micronaut.http.annotation.Get</span>
<span class="nd">@Controller</span><span class="o">(</span><span class="s2">"/api/todo"</span><span class="o">)</span>
<span class="kd">class</span> <span class="nc">TodoController</span> <span class="o">{</span>
<span class="nd">@Get</span><span class="o">(</span><span class="s2">"/{id}"</span><span class="o">)</span>
<span class="n">Todo</span> <span class="nf">getTodo</span><span class="o">(</span><span class="kt">int</span> <span class="n">id</span><span class="o">)</span> <span class="o">{</span>
<span class="c1">//Do something with the id from the URI</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>The <code class="language-plaintext highlighter-rouge">@Get</code> annotation is placed onto the method that will handle the GET action for the combined URL in the <code class="language-plaintext highlighter-rouge">@Controller</code>
and <code class="language-plaintext highlighter-rouge">@Get</code> annotations. Additional annotations exist for other HTTP methods (POST, PUT, etc.). Path variables are supported
in URLs and consist of a placeholder (<code class="language-plaintext highlighter-rouge">{id}</code> in this case) and a matching method parameter. Objects returned from controller
methods will automatically be converted to JSON.</p>
<h2 id="beans">Beans</h2>
<p>Beans can be defined using annotations on a class. Like with controllers, beans will be found and registered via classpath
scanning. There are several different annotations (<code class="language-plaintext highlighter-rouge">@Singleton</code>, <code class="language-plaintext highlighter-rouge">@Prototype</code>, etc.) for creating beans with different scopes.
So, for example, I can create a service using the Singleton annotation.</p>
<div class="language-groovy highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">javax.inject.Singleton</span>
<span class="nd">@Singleton</span>
<span class="kd">class</span> <span class="nc">TodoService</span> <span class="o">{</span>
<span class="c1">//Provide some implementation</span>
<span class="o">}</span>
</code></pre></div></div>
<h2 id="dependency-injection">Dependency Injection</h2>
<p>Dependency injection is provided using the JSR-330 <code class="language-plaintext highlighter-rouge">@Inject</code> annotation. Unlike other frameworks, Micronaut performs
dependency injection at compile time. This avoids the use of reflection/proxies and contributes to faster startup
times.</p>
<p>The <code class="language-plaintext highlighter-rouge">@Inject</code> annotation can be used to inject dependencies via constructor injection, field injection, and method parameters.</p>
<p>Extending the controller example from before, we can inject a service as follows:</p>
<div class="language-groovy highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">io.micronaut.http.annotation.Controller</span>
<span class="kn">import</span> <span class="nn">io.micronaut.http.annotation.Get</span>
<span class="kn">import</span> <span class="nn">javax.inject.Inject</span>
<span class="nd">@Controller</span><span class="o">(</span><span class="s2">"/api/todo"</span><span class="o">)</span>
<span class="kd">class</span> <span class="nc">TodoController</span> <span class="o">{</span>
<span class="n">TodoService</span> <span class="n">todoService</span>
<span class="nd">@Inject</span>
<span class="n">TodoController</span><span class="o">(</span><span class="n">TodoService</span> <span class="n">todoService</span><span class="o">)</span> <span class="o">{</span>
<span class="k">this</span><span class="o">.</span><span class="na">todoService</span> <span class="o">=</span> <span class="n">todoService</span>
<span class="o">}</span>
<span class="nd">@Get</span><span class="o">(</span><span class="s2">"/{id}"</span><span class="o">)</span>
<span class="n">Todo</span> <span class="nf">getTodo</span><span class="o">(</span><span class="kt">int</span> <span class="n">id</span><span class="o">)</span> <span class="o">{</span>
<span class="c1">//Do something with the id from the URI</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<h2 id="conclusion">Conclusion</h2>
<p>This quick overview just barely scratches the surface of the functionality available already in Micronaut. The
<a href="https://docs.micronaut.io/snapshot/guide/index.html">user guide</a> is comprehensive and provides a lot of great information
for all of the functionality. Developers coming to Micronaut from Spring Framework will find it very familiar.</p>
<p>Considering that the framework hasn’t reached an official 1.0 release yet, it already seems very powerful. I look forward
to seeing how it continues to evolve and grow.</p>
<p><small>
<strong>Updated 2018-07-30</strong>: Thanks to <a href="https://twitter.com/Schlogen">Jim Kleeh</a> for pointing out on Twitter that annotations
are not found via classpath scanning, but instead this happens at compile time.
</small></p>Michael BaldwinMicronaut is a new open source Java/JVM framework for creating microservice applications. Development is being led by the creators of the Grails framework and is backed by Object Computing. The project is actively working toward its official 1.0 release.Thoughts on attending conferences2018-06-17T03:45:00+00:002018-06-17T03:45:00+00:00https://michael.codes/posts/thoughts-on-conferences<p>Since 2016 I have attended five developer conferences in my area.
With a few conferences behind me, I thought I would share my thoughts and advice for someone
looking to attend a conference for the first time. This article is just my experience, and I am
no expert. So, your experiences may vary.</p>
<h2 id="why-attend-a-conference">Why attend a conference?</h2>
<p>If you have never gone to a conference, you may be wondering why you would want to. Today a lot of
conferences record their sessions and post them on YouTube, but to me watching a video online doesn’t
have the same impact.</p>
<ul>
<li><strong><em>Learn something new.</em></strong> This is the reason most people think of first. Conferences are a
great place to get introduced to new technologies. The sessions aren’t the place to fully learn
a technology, but they are a good place to determine which technologies you should be learning.</li>
<li><strong><em>Meet new people.</em></strong> Conferences are a great place to network and meet new people working
in technology and learn from them. Where else will you find so many people with similar
interests all in one place?</li>
<li><strong><em>Be inspired.</em></strong> A nice side effect of attending a conference is a boost in motivation to
learn a new technology or to work on side projects.</li>
</ul>
<h2 id="how-do-i-get-ready-for-the-conference">How do I get ready for the conference?</h2>
<p>Conference session schedules are usually available online at least a few weeks in advance. Look over
the schedule and try to narrow down which talks you are most interested in during each time slot. Doing this
in advance really helps you know where you need to go next.</p>
<p>On the day of the conference, I usually try to keep the items I carry with me to a minimum. Carrying around
a heavy bag all day is a good way to make the event less enjoyable. So, what do I typically bring with me
to a conference?</p>
<ul>
<li><strong><em>A backpack.</em></strong> To me, a backpack of some kind is essential when I am going to be walking around a conference
center all day. I have a full sized backpack as well as a smaller “sling” type bag that is easier to carry.
I generally only take the larger bag if I am bringing a laptop, or for the first day of a conference if I
know they will be giving out t-shirts, etc. at registration.</li>
<li><strong><em>Phone charger/battery pack.</em></strong> This one is pretty obvious, you don’t want to run out of power half-way
through the day.</li>
<li><strong><em>Notebook and pens.</em></strong> I still prefer taking notes on paper. I feel like I can write faster and remember
the information better this way. Also, the notebook doesn’t provide any distractions that a laptop or tablet
would.</li>
<li><strong><em>A snack, hard candy, chewing gum.</em></strong> I always pack a few snack items just in case I get hungry. Also,
mints and chewing gum are good for making sure you don’t have bad breath after lunch.</li>
<li><strong><em>My laptop.</em></strong> I usually only take a laptop with me if I know there is going to be an interactive “workshop”
type session. Carrying around the laptop all day can be tiring, and it can be too tempting to sit down
and focus on the screen and not what is going on around me.</li>
</ul>
<h2 id="im-at-a-conference-now-what">I’m at a conference, now what?</h2>
<ul>
<li>
<p><strong><em>Talk to people.</em></strong> This one is really hard for someone like me who is naturally introverted. Meeting
new people with similar interests is one of the most valuable parts of a conference. Try introducing yourself
to someone in the hallway, or at lunch. You never know who you might meet.</p>
</li>
<li>
<p><strong><em>Branch out.</em></strong> Don’t stick to only sessions that are directly applicable to your work.
I have started trying to go to at least one or two sessions just because they sound interesting.
For example, at a recent conference, I went to a talk on machine learning. It isn’t a
technology I see myself using anytime soon, but it was enlightening anyway.</p>
</li>
</ul>
<p>I hope this has been interesting or helpful to someone. The most important thing is to go and both have fun
and come back feeling like you have gained something from being there.</p>
<p>If you want to read more about the conferences I have attended, <a href="https://michael.codes/categories/#conference">click here</a>
to view the summary posts about them.</p>Michael BaldwinSince 2016 I have attended five developer conferences in my area. With a few conferences behind me, I thought I would share my thoughts and advice for someone looking to attend a conference for the first time. This article is just my experience, and I am no expert. So, your experiences may vary.Nexus 5x Boot Loop Adventures2017-09-19T01:35:00+00:002017-09-19T01:35:00+00:00https://michael.codes/posts/nexus-5x-bootloop<p>I’ve had a Google Nexus 5x phone for almost two years. I pre-ordered it as soon
as it was announced, and have generally been really happy with the phone. Last
weekend I woke up one morning to find my phone powered off and it wouldn’t
turn back on at all. This begins my adventure trying to troubleshoot my phone.</p>
<p>After leaving the phone plugged into the power adapter I was eventually
able to get the phone to power on enough to show the Google logo. However,
it would always freeze up during the Android OS boot and then restart.
Only once did the device boot all the way and seem to function a while
before crashing again.</p>
<p>I was sometimes able to get into the fastboot and recovery menus. So,
just to see if it helped, and assuming my data was lost anyway, I attempted
to wipe the cache and do a factory data reset which didn’t really help.</p>
<p>Fortunately, I was able to get the device to boot again and had an
opportunity to enable OEM unlocking on the bootloader.</p>
<p>After many Google searches I found others talking about experiencing the
same “boot loop” issue that sounded exactly like what I was experiencing.
Most of the posts concluded that the phone was deas and provided little
help or encouragement.</p>
<p>At this point my research lead to learning more about the CPU being used.
The Nexus 5x uses a <a href="https://www.qualcomm.com/products/snapdragon/processors/808">Snapdragon 808</a>
processor which has six-cores in a big.LITTLE configuration. It has two
Cortex A57 “big” cores and four Cortex A53 “little” cores. This design is
used to balance power usage and performance.</p>
<p>The posts indicated that the problem in this phone and others using this
chip were caused by malfunctions developing in the two big cores. I found a
potential “<em>fix</em>” in the <a href="https://forum.xda-developers.com/nexus-5x/general/untested-nexus-5x-bootloop-death-fix-t3641199">xda-developers</a>
forum. The suggestion was utilizing a customized boot image that disables
the two big cores and lets the phone operate on the four remaining little
cores.</p>
<p>So, at this point I decided to give it a try just to see what happend.
I utilized the fastboot utility to unlock my bootloader, and then followed
the article’s instructions to flash the new boot image.</p>
<p>After flashing the phone started up immediately… no boot loop!</p>
<p>Initially this seemed pretty promising. I rebooted the phone many times
and only had a few instances of it crashing during start up. I’ve also
had it freeze up and reboot mid-use a couple of times. I definitely wouldn’t call
this a fix, but it is a workaround to make the phone at least semi-functional.</p>
<p>At this point I still don’t have enough confidence in it being reliable enough
to switch my service back. So, I will probably keep using an older phone
until Google’s new phone announcement. I’m sad to see the old Nexus 5x go, it
really was a great phone. Perhaps a Pixel 2, or even the essential phone could
be in my future.</p>
<p>Regardless of the outcome, this was definitely an interesting learning experience
troubleshooting hardware, and flashing new software onto a phone!</p>Michael BaldwinI’ve had a Google Nexus 5x phone for almost two years. I pre-ordered it as soon as it was announced, and have generally been really happy with the phone. Last weekend I woke up one morning to find my phone powered off and it wouldn’t turn back on at all. This begins my adventure trying to troubleshoot my phone.Scenic City Summit 20172017-09-17T01:26:00+00:002017-09-17T01:26:00+00:00https://michael.codes/posts/scenic-city-summt-2017<p>At the end of June I attended the second annual <a href="https://www.sceniccitysummit.com/">Scenic City Summit</a>
in Chattanooga, TN with some friends. This year the conference grew significantly
in size and attendance and moved to the Chattanooga Convention Center
from the UTC campus.</p>
<p>This year’s keynote was (like last year) presented by
<a href="https://www.twitter.com/housecor">Cory House</a>. The topic was “<em>The Reusable
JavaScript Revolution</em>” and covered three different revolutions: npm packages,
starter kits, and components. He pointed out the value of starter kits in
simplifying the setup of JavaScript projects. Development is also moving
toward component oriented architectures with frameworks like ReactJS and
the new web components standard.</p>
<p class="quote-block">
The future is here, its just not evenly distributed.
<span class="quote-block-author">
- Cory House
</span>
</p>
<p><a href="https://github.com/emily-e/basements-and-beasties">Emily Estes</a>
talked about reimplementing a 1980s text adventure game in a
variety of programming languages ranging from common languages like Java
and Python to Ada. There was even a version written entirely in SQL.</p>
<p><a href="https://www.twitter.com/elpapapollo">Jeremy Fairbank</a> presented a different way of building web front-ends with Elm.
Elm is a functional programming language that transpiles to JavaScript and is
designed for building web applications. It provides one framework for implementing
the Model-View-Update pattern. The language has strong static types and no
runtime exceptions in practice.</p>
<p>Another talk from Cory House promised to teach us React before lunch. This
framework has become very popular recently. Facebook recomments using the
create-react-app utility for starting new React projects. The tool handles
configuration of the required build chain.</p>
<p>Following lunch I learned about using Rx Java with Android in a talk by
<a href="https://twitter.com/mantamay">Andrew May</a>. Rx Java is a framework for
reactive programming in Java. The framework consists of defining Observables
that emit items and Observers that react when data is emitted. The talk
focused on uses with Android, but the same concepts could be applied to
any Java application.</p>
<p><a href="https://twitter.com/pcameronpresley">Cameron Presley</a> talked about how to
have code reviews developers actually want. He talked about the key things to
look at when reviewing code: quality, readability, maintainability, and style.
He also pointed out the value of the “30% review” earlier in the development
process to catch problems earlier.</p>
<p>Jeremy Fairbank had another talk about getting started with redux. Redux is
a predictable state container for JavaScript that is commonly used with React.
The framework stores the application state and manages its updating via actions.</p>
<p>This year’s closing keynote was by <a href="https://twitter.com/reverentgeek">David Neal</a>
and was a guide for the reluctant leader. David’s talks are always both entertaining
and informative. This time he had plenty of stories about his journey to being a leader
and gave lots of advice for time managers from the perspective of an introvert.</p>
<p class="quote-block">
Life is too short to let things stay the way they are.
<span class="quote-block-author">
- David Neal
</span>
</p>
<p>The conference has definitely grown a lot from its first year and was a lot of fun.
I look forward to seeing how things continue to grow in the future.</p>Michael BaldwinAt the end of June I attended the second annual Scenic City Summit in Chattanooga, TN with some friends. This year the conference grew significantly in size and attendance and moved to the Chattanooga Convention Center from the UTC campus.