<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	
	xmlns:georss="http://www.georss.org/georss"
	xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
	>

<channel>
	<title>Topic kotlin-showoff | Hey, ruX is here.</title>
	<atom:link href="https://rux.vc/tags/kotlin-showoff/feed/" rel="self" type="application/rss+xml" />
	<link>https://rux.vc</link>
	<description>Delivering things - from code to product</description>
	<lastBuildDate>Sat, 16 Nov 2019 16:07:58 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.4.8</generator>
<site xmlns="com-wordpress:feed-additions:1">162978439</site>	<item>
		<title>Functional Kotlin part 4: collections manipulation</title>
		<link>https://rux.vc/2019.11/functional-kotlin-part-4-collections-manipulation/</link>
					<comments>https://rux.vc/2019.11/functional-kotlin-part-4-collections-manipulation/#respond</comments>
		
		<dc:creator><![CDATA[ruX]]></dc:creator>
		<pubDate>Sat, 02 Nov 2019 13:07:48 +0000</pubDate>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[kotlin]]></category>
		<category><![CDATA[collections]]></category>
		<category><![CDATA[iterable]]></category>
		<category><![CDATA[kotlin-showoff]]></category>
		<category><![CDATA[stdlib]]></category>
		<guid isPermaLink="false">https://rux.vc/?p=3451</guid>

					<description><![CDATA[<p>This is a part 4 of the #kotlin-showoff series and it's going to be about the standard functions over the collections(mostly iterables to be precise) allowing developer to express data modification in the clean and functional way. General convention Although one might think that kotlin has inherited all the base collection types from the Java ... <a title="Functional Kotlin part 4: collections manipulation" class="read-more" href="https://rux.vc/2019.11/functional-kotlin-part-4-collections-manipulation/" aria-label="More on Functional Kotlin part 4: collections manipulation">Read more</a></p>
The post <a href="https://rux.vc/2019.11/functional-kotlin-part-4-collections-manipulation/">Functional Kotlin part 4: collections manipulation</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></description>
										<content:encoded><![CDATA[<p>This is a part 4 of the <a href="/tags/kotlin-showoff">#kotlin-showoff</a> series and it's going to be about the standard functions over the collections(mostly iterables to be precise) allowing developer to express data modification in the clean and functional way.</p>

<h2>General convention</h2>
<p>Although one might think that kotlin has inherited all the base collection types from the Java it's not quite true. Kotlin transparently maps existing Java collections into the Kotlin by using some tricks such as typealiasing. Collections hierarchy in Kotlin make code even more safer by imposing separation between mutable and immutable data structures. Take a look on the interfaces diagram:</p>
<span id="more-3451"></span>
<p><img decoding="async" src="https://rux.vc/wp-content/uploads/2019/10/collections-diagram.png" alt="diagram originally posted on the kotlinlang.org" /></p>
<p>Having dedicated interfaces for immutable collections makes expressions are purely functional - no need to worry if api consumer modifies list on the way or even worse, attempt to insert into the immutable collection(goodbye <code>UnsupportedOperationException</code>!). Indeed, immutability is enforced in <strong>compile time</strong> by contract.</p>
<h3>A note about Iterable vs Sequence</h3>
<p>Those are very similar types of the base entities even with the same signatures, let's take a look</p>
<pre><code class="language-kotln">public interface Sequence&lt;out T&gt; {
    public operator fun iterator(): Iterator&lt;T&gt;
}

public interface Iterable&lt;out T&gt; {
    public operator fun iterator(): Iterator&lt;T&gt;
}</code></pre>
<p>Those two base classes define the way data will be processed in the chain of the calls:</p>
<ul>
<li>Operations on <code>Iterable</code> produce result immideatelly, so the <em>full</em> intermideate result will be passed between calls in the chain. The result is evaluated <strong>eagerly</strong> after each step.</li>
<li>Operations on the <code>Sequence</code> treat data items comming thorough as it would be an infinite stream, the closest analogy would be java8 <code>Stream</code> or <code>RxObservable</code>.  Items passed via the chain of the calls one by one. Result is evaluated <strong>lazily</strong>.</li>
</ul>
<p>As for now we focus on the <code>Iterable</code> and it's descendants(<code>Collection</code>, <code>List</code>, <code>Map</code>,  etc..) . Luckily, <em>many</em> operations exist for both interfaces with exactly the same  signatures</p>
<h3>Simple list transformations <code>filter</code>, <code>map</code>, <code>forEach</code></h3>
<p>Those are the probably the most widely used operators and they do exactly after their name. The provided function is applied to the each element of the operation</p>
<pre><code class="language-kotlin">val adminNames = users
  .filter { it.isAdmin }
  .map { it.name }

pupils.forEach { 
  println(&quot;${it.name}: ${it.score}&quot;)
}</code></pre>
<h3><code>filter*</code> and <code>map*</code> families</h3>
<p>There are <a href="https://github.com/JetBrains/kotlin/blob/master/libraries/stdlib/common/src/generated/_Collections.kt">way more </a> similar operations provided in the Kotlin stdlib giving extra flexibility when it need:</p>
<pre><code class="language-kotlin">val userList = users
  .filterNotNul()
  .filterNot { it.isBanned }
  .mapTo(mutableHashSet()) { it.userId }
  .mapIndexed { (idx, userId) -&gt; &quot;#${idx}: {it.userId}&quot; }</code></pre>
<p>In many occasions you'll find the same pattern - <code>verb [not] [indexed] [to]</code>. No need to memorise - the names come out intuitively:
<img decoding="async" src="https://rux.vc/wp-content/uploads/2019/10/Screenshot-from-2019-10-29-22-42-56.png" alt="" />
<img decoding="async" src="https://rux.vc/wp-content/uploads/2019/10/Screenshot-from-2019-10-29-22-47-14.png" alt="" /></p>
<h3>Operations returning single element: <code>first</code>, <code>last</code>, <code>single</code>, <code>elementAt</code>, <code>get</code></h3>
<p><code>first</code> and <code>last</code> return first and last elements (obviously). </p>
<pre><code class="language-kotlin">val firstUser = users.first()
val firstAdminUser = users.first { it.isAdmin }
val lastBannedUser = users.last { it.isBanned }</code></pre>
<p><code>single</code> returns one element and throws exception if more than 1 element in collection matches the predicate</p>
<pre><code class="language-kotlin">val oneLove = listOf(&quot;java&quot;, &quot;kotlin&quot;,  &quot;javascript&quot;).singleOrNull { it == &quot;kotlin&quot; } </code></pre>
<p>Also those operations can have return alternative value - provided by closure or null:</p>
<pre><code class="language-kotlin">val oneLove = languages.singleOrNull { it == &quot;kotlin&quot; }
val tenthWinnerName = user.getOrElse(10) { &quot;NO WINNER&quot; }
val secondPerson = user.getOrNull(2)</code></pre>
<h3>Aggregation operations <code>count</code>, <code>average</code>, <code>min</code>, <code>max</code></h3>
<p>Again, intuitively those operations perform aggregations:</p>
<pre><code class="language-koltlin">val avgScore = pupils.average { it.score }
val topStudent = pupils.max { it.score }
val channagingStudent = pupils.min { it.score }</code></pre>
<h3>Conditional oprations <code>all</code>, <code>none</code>, <code>count</code>, <code>any</code></h3>
<pre><code class="language-kotlin">val numberOfTopStudents = pupils.count { it.score &gt; 4.5 }
val allPassed = pupils.all { it.score &gt; 2.0 }
val hasNeedleInHaystack = heap.any { it.object == NEEDLE }
val allGood = results.none { it.error != null }</code></pre>
<h3>List to Map transformation <code>associate*</code>,  <code>groupBy</code></h3>
<p>Both operations produce a <code>Map</code> and they are different on how keys are collided. While <code>assciate*</code> simply overwrites existing value with associated key, <code>groupBy</code> adds value to the list of values:</p>
<pre><code class="language-kotlin">val usersById = users.associate { it.id to it } // result type: Map&lt;UserId, User&gt;
val usersById = users.associateBy { it.id } // same output
val pupilsByScore = pupils.groupBy { it.score } // result type Map&lt;Int, List&lt;Pupil&gt;&gt;
</code></pre>
<h3>Many more</h3>
<p>There a way more functional operations over collections are available in Kotlin stdlib such as <code>fold</code>, <code>reduce</code>, <code>minus(-)</code>, <code>plus(+)</code>, <code>contains(in)</code> etc:</p>
<pre><code class="language-kotlin">// result - list of the both users
val allUsers = fbUsers + twitterUsers 

// result - elements of allUserIds which are not in bannedUsersIds
val activeUserIds = allUserIds - bannedUsersIds 

// result - the longest length of the name
val longestName = names.reduce { longest, item -&gt; if (longest.length &lt; item.length) item else longest }

// result - same as above, the longest length of the name
val longestLength = names.map(String::length).fold(0, ::max))

// result - if Wally was there
val isWallyLovesKotlin = &quot;Wally&quot; in kotlinLovers</code></pre>
<p>Those extension functions are very intuitive and widely used, essentially can cover most of the everyday tasks. </p>
<h2>Conclusion</h2>
<p>Kotlin collection functions provide a lot of flexibility to express your ideas and business logic in very concise, clear and functional way</p>
<p>Hopefully you found this article useful for you, please check out other posts by <a href="/tags/kotlin-showoff">#kotlin-showoff</a>  hashtag</p>The post <a href="https://rux.vc/2019.11/functional-kotlin-part-4-collections-manipulation/">Functional Kotlin part 4: collections manipulation</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></content:encoded>
					
					<wfw:commentRss>https://rux.vc/2019.11/functional-kotlin-part-4-collections-manipulation/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3451</post-id>	</item>
		<item>
		<title>Functional kotlin part 3: scoping functions</title>
		<link>https://rux.vc/2019.10/functional-kotlin-part-3-scoping-functions/</link>
					<comments>https://rux.vc/2019.10/functional-kotlin-part-3-scoping-functions/#respond</comments>
		
		<dc:creator><![CDATA[ruX]]></dc:creator>
		<pubDate>Wed, 02 Oct 2019 20:57:35 +0000</pubDate>
				<category><![CDATA[kotlin]]></category>
		<category><![CDATA[functional programming]]></category>
		<category><![CDATA[kotlin-showoff]]></category>
		<category><![CDATA[lambda]]></category>
		<category><![CDATA[productivity]]></category>
		<guid isPermaLink="false">https://rux.vc/?p=3427</guid>

					<description><![CDATA[<p>In the part 3 of the series of the posts about kotlin we going to look into the one of the intensively used kotlin extension functions from the standard library - they allow to write very expressive and safe, functionally-looking code. For folks who got lost on the word "extension functions" - it's a way ... <a title="Functional kotlin part 3: scoping functions" class="read-more" href="https://rux.vc/2019.10/functional-kotlin-part-3-scoping-functions/" aria-label="More on Functional kotlin part 3: scoping functions">Read more</a></p>
The post <a href="https://rux.vc/2019.10/functional-kotlin-part-3-scoping-functions/">Functional kotlin part 3: scoping functions</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></description>
										<content:encoded><![CDATA[<p>In <g class="gr_ gr_5 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-del replaceWithoutSep" id="5" data-gr-id="5">the part</g> 3 of <a href="/tags/kotlin-showoff">the series of the</a> posts about kotlin we going to look into <g class="gr_ gr_6 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-del replaceWithoutSep" id="6" data-gr-id="6">the one</g> of the intensively used kotlin <strong>extension</strong> functions from the standard library - they allow to write very expressive and safe, functionally-looking code.</p>



<p>For folks who got lost on the word "extension functions" - it's a way to <strong>attach</strong> a <em>function</em> or <em>property</em> to the instances of the existing classes. For example, <code>val d = 10.twice()</code>It's very much like <g class="gr_ gr_8 gr-alert gr_gramm gr_hide gr_inline_cards gr_run_anim Grammar multiReplace replaceWithoutSep" id="8" data-gr-id="8">a classic <g class="gr_ gr_12 gr-alert gr_gramm gr_inline_cards gr_run_anim Style multiReplace" id="12" data-gr-id="12">Java  <code>Util</code></g></g><g class="gr_ gr_8 gr-alert gr_gramm gr_hide gr_inline_cards gr_disable_anim_appear Grammar multiReplace replaceWithoutSep" id="8" data-gr-id="8"><g class="gr_ gr_12 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Style multiReplace" id="12" data-gr-id="12"><g class="gr_ gr_12 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Style multiReplace" id="12" data-gr-id="12">  classes</g></g> with method <code>twice(int)</code> but done in a very clean way. Visually it looks like you're calling a member of the class, but in reality, the compiler calls your function passing receiver as an argument.</g> </p>



<span id="more-3427"></span>



<h2 class="wp-block-heading">T.<code>let</code></h2>



<p><code>let</code> allows passing given reciever into the parameter of the lambda, returns result from it. Essentially it's an <code>map</code> operator on the single value</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">val imageData = db.getUserById(userId)
    ?.let { it.getProfilePicture().url }
    ?.let { fetchData(it) }</code></pre>



<h3 class="wp-block-heading">How to use?</h3>



<p>It's very useful when it comes to the conditional on nullable object, think of functional replacement for <code>if (user != null) user.ban()</code>:</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">user?.let { it.ban() }
// or even
user?.let(::ban)</code></pre>



<p>Often we use expressions in the string interpolation, <code>.let</code> can be very handy:</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">println(&quot;Hello ${db.getUser(id)?.let { it.name } ?: &quot;NONAME&quot;}&quot;)</code></pre>



<hr class="wp-block-separator"/>



<h2 class="wp-block-heading">T.<code>apply</code></h2>



<p><code>apply</code> calls given lambda in <strong>the context</strong> of receiver, similar to the <code>with</code> found in JavaScript and Groovy.</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">User().apply {
    name = &quot;user name&quot;
    password = &quot;qwerty&quot;
}</code></pre>



<h3 class="wp-block-heading">How to use?</h3>



<p>I found it's a way to <s>patch</s> <strong>encapsulate configuration</strong>/finish object initialisation. It helps to perform number of operations within lambda block which are logically related to the operation such as factory initialisation or object creation. <code>apply</code> returns the receiver object(object it was called on)</p>



<p>So instead of</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">val awsS3Client = AwsS3Client()
val credentials = AwsCredentialsFactory(&quot;key&quot;, &quot;secret&quot;)
credentials.setForceHttps(true)
awsS3Client.credentials = credentials
awsS3Client.bucket = &quot;my_bucket&quot;</code></pre>



<p>We can have nicely organized initialization block:</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">val awsS3Client = AwsS3Client().apply {
    credentials = AwsCredentialsFactory(&quot;key&quot;, &quot;secret&quot;).apply {
        setForceHttps(true)
    }
    bucket = &quot;my_bucket&quot;
}
</code></pre>



<p>Nice and clean, without messy noise and scope pollution!</p>



<hr class="wp-block-separator"/>



<h2 class="wp-block-heading">T<code>.also</code> </h2>



<p>It behaves exactly as <code>.let</code> with one exception - with return result. <code>.also</code> takes receiver and passes it as an argument for the given lambda, returning the same receiver</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">val bannedUser = db.getUserById(userId)
   .also { println(&quot;Got user $it&quot;) }
   .ban()</code></pre>



<h3 class="wp-block-heading">How to use?</h3>



<p>From my experience it can be used for debugging - as demonstrated above. Also, it can be used a replacement for <g class="gr_ gr_8 gr-alert gr_gramm gr_inline_cards gr_run_anim Style multiReplace" id="8" data-gr-id="8">the </g><code>.apply</code><g class="gr_ gr_8 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Style multiReplace" id="8" data-gr-id="8">,</g> one can say it's more clear - based on the example for <code>.apply</code>:</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">val awsS3Client = AwsS3Client().also {
    it.credentials = AwsCredentialsFactory(&quot;key&quot;, &quot;secret&quot;).apply {
        it.setForceHttps(true)
    }
    it.bucket = &quot;my_bucket&quot;
}</code></pre>



<hr class="wp-block-separator"/>



<h2 class="wp-block-heading">T<code>.run</code> / <code>with()</code></h2>



<p>These have very similar <g class="gr_ gr_5 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling multiReplace gr-progress sel" id="5" data-gr-id="5">b</g>ehaviour - they both change the context of the function but <g class="gr_ gr_7 gr-alert gr_gramm gr_inline_cards gr_run_anim Style multiReplace" id="7" data-gr-id="7">unlike .</g><code>apply</code> the result of the function would be something lambda returned</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">val userId = User().run {
    name = &quot;username&quot;
    password = &quot;foobar&quot;
    db.save(this).id
}

val userId = with(User()) {
    name = &quot;username&quot;
    password = &quot;foobar&quot;
    db.save(this).id
}</code></pre>



<p>These two have identical behaviour - in both cases object is initialised, saved and generated id is returned - the result of the last line expression</p>



<h3 class="wp-block-heading">How to use?</h3>



<p>Well, I didn't find it used often in my code, but the example above may give you some idea</p>



<hr class="wp-block-separator"/>



<h2 class="wp-block-heading">Combo</h2>



<p>Some examples from the real projects</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">// filter out images with faces, print debug info, annotate 
// image with labels and filter images by stop words
val images = allImages
    // filter pics with faces if necessary
    ?.let { if (allowFaces) it else withoutFaces(word, it) }
    ?.also { log.info(&quot;findImageForWord: got ${it.size} pics after face filtering&quot;) }
    // image labelling
    ?.let { findLabels(word, it) }
    // exclude stop list words
    ?.filterNot { it.normalizedLabels.any { it in stopList } }


// Prepare video upload request for the YouTube API:
val video = Video().also {
    it.snippet = VideoSnippet().also {
        it.set(&quot;categoryId&quot;, &quot;27&quot;)
        it.set(&quot;description&quot;, description)
        it.set(&quot;title&quot;, title)
        it.set(&quot;tags&quot;, tags)
    }
    it.status = status
}
</code></pre>



<p>I hope you found this article useful for you. Check out <a href="/tags/kotlin-fun">other posts</a> about functional constructions to get the most out of kotlin</p>The post <a href="https://rux.vc/2019.10/functional-kotlin-part-3-scoping-functions/">Functional kotlin part 3: scoping functions</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></content:encoded>
					
					<wfw:commentRss>https://rux.vc/2019.10/functional-kotlin-part-3-scoping-functions/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3427</post-id>	</item>
		<item>
		<title>Functional kotlin part 2: elvis operator</title>
		<link>https://rux.vc/2019.09/functional-kotlin-part-2-elvis-operator/</link>
					<comments>https://rux.vc/2019.09/functional-kotlin-part-2-elvis-operator/#respond</comments>
		
		<dc:creator><![CDATA[ruX]]></dc:creator>
		<pubDate>Wed, 25 Sep 2019 09:17:06 +0000</pubDate>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[kotlin]]></category>
		<category><![CDATA[Quick notes]]></category>
		<category><![CDATA[kotlin-showoff]]></category>
		<guid isPermaLink="false">https://rux.vc/?p=3411</guid>

					<description><![CDATA[<p>Continuing series of posts #kotlin-showoff about functional constructions in kotlin I want to demostrate use of elvis operator Essentially, elvis operator lvalue ?: rexpression is returning left value if it's not null or executes rexpression otherwise. The crazy thing about kotlin is most of the constructions are expressions and that gives another way to express ... <a title="Functional kotlin part 2: elvis operator" class="read-more" href="https://rux.vc/2019.09/functional-kotlin-part-2-elvis-operator/" aria-label="More on Functional kotlin part 2: elvis operator">Read more</a></p>
The post <a href="https://rux.vc/2019.09/functional-kotlin-part-2-elvis-operator/">Functional kotlin part 2: elvis operator</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></description>
										<content:encoded><![CDATA[<p>Continuing series of posts <a href="/tags/kotlin-showoff/">#kotlin-showoff</a> about functional constructions in kotlin I want to <g class="gr_ gr_17 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="17" data-gr-id="17">demostrate</g> use of <g class="gr_ gr_25 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="25" data-gr-id="25">elvis</g> operator </p>



<p>Essentially, elvis operator <strong>lvalue ?: rexpression</strong> is returning left value if it's not <code>null</code> or executes <strong>rexpression</strong> otherwise. The crazy thing about kotlin is most of the constructions are expressions and that gives another way to express business logic.</p>



<span id="more-3411"></span>



<h3 class="wp-block-heading">Returning alternative value</h3>



<p>In the simplest case we can return alternative value if left value is <code>null</code>, for example</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">val userList = cache.get(userId) ?: fetch(userId)</code></pre>



<p>Literally means: get value of <code>cache.get(userId)</code> if it's not null or <code>fetch(userId)</code> </p>



<p>In Java it can be expressed as</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">List&lt;User&gt; userList = cache.get(userId);
if (userList == null) userList = fetch(userId);</code></pre>



<p>Also, it's possible to chain <g class="gr_ gr_3 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="3" data-gr-id="3">elvis</g> operators</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">val userList = memoryCache.get(userId) 
     ?: diskCache.get(userId)
     ?: fetch(userId)</code></pre>



<p>Looks lovely and clean, isn't it?</p>



<h3 class="wp-block-heading">Early return with elvis</h3>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">fun displayUsers() {
    val userList = cache.get(userId) 
        ?: return
    updateUiWithNewUserList(userList)
}</code></pre>



<p>In this case return if <code>userList</code> is null function will return immideatelly</p>



<h3 class="wp-block-heading">Throw exception with <g class="gr_ gr_11 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="11" data-gr-id="11">elvis</g> operator</h3>



<p>In Java code we often need to manage an exceptional situation and allow callers to handle it themselves. Take a look on this example:</p>



<pre class="wp-block-prismatic-blocks"><code class="language-java">void displayUsers() {
    List&lt;User&gt; userList = cache.get(userId);
    if (userList == null) 
        throw new NoDataAvailableException()
    . . . 
}</code></pre>



<p>Employing elvis operator in kotlin it looks more concise and logic is encapsulated within one expression:</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">fun displayUsers() {
    val userList = cache.get(userId) 
        ?: throw NoDataAvailableException()
    . . .
}</code></pre>



<p>Looks cleaner, isn't it?</p>



<h3 class="wp-block-heading">Elvis operator with in loops</h3>



<p>In the same way as we used early return it's possible to make elvis to work with <code>break</code> and <code>continue</code>, in case if you're <em>still</em> using loops</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">fun top10Score(users: List&lt;User&gt;): Int {
    var totalScore = 0
    for(i in 0 until Math.min(users.size, 10)) {
        val score = users[i].gameProgress?.score 
            ?: continue
        totalScore += score
    }
    return totalScore
}</code></pre>



<p>If either <code>gameProgress</code> or <code>score</code> are <code>null</code> loop will continue to the next element. <br>By the way, there is a <strong>way</strong> expressive functional way to implement the same logic:</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">fun top10Score(users: List&lt;User&gt;): Int = users
    .take(10)
    .fold(0) { acc, it -&gt; acc + (it.gameProgress?.score ?: 0) }</code></pre>



<h3 class="wp-block-heading">It works not only for nullable types</h3>



<p>Kotlin has numerous <strong>extension functions</strong> allowing to express flow in the concise and functional manner. We'll dive into this topic in the following articles. </p>



<p>But here is a spoiler for you, say it's need to throw exception in validator when user didn't provide name or it was empty. From data point of view <code>null</code> isn't same as empty string, empty string isn't same as a string full of spaces. But in our business logic it's <strong>practically the same</strong> since no name is provided. Here is an example of handling this situation:</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">val name = user.name?.takeIf(String::isNotBlank)
    ?: throw UserNameIsEmptyException()</code></pre>



<p><code>takeIf</code> returns receiver object if predicate is <code>true</code>. Even <code>user.name</code> is not <code>null</code> but consist of empty string <code>takeIf</code> will return <code>null</code> because it doesn't satisfy condition. Exception will be thrown in this case and it's guaranteed by compiler that <code>name</code>  is not null</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p>Elvis operator in kotlin is very powerful and helps to handle conditional logic naturally within the data flow</p>The post <a href="https://rux.vc/2019.09/functional-kotlin-part-2-elvis-operator/">Functional kotlin part 2: elvis operator</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></content:encoded>
					
					<wfw:commentRss>https://rux.vc/2019.09/functional-kotlin-part-2-elvis-operator/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3411</post-id>	</item>
		<item>
		<title>Functional kotlin part 1: safe calls</title>
		<link>https://rux.vc/2019.09/functional-kotlin-part-1-nullable-safe-calls/</link>
					<comments>https://rux.vc/2019.09/functional-kotlin-part-1-nullable-safe-calls/#comments</comments>
		
		<dc:creator><![CDATA[ruX]]></dc:creator>
		<pubDate>Tue, 24 Sep 2019 18:37:36 +0000</pubDate>
				<category><![CDATA[kotlin]]></category>
		<category><![CDATA[Quick notes]]></category>
		<category><![CDATA[kotlin-showoff]]></category>
		<guid isPermaLink="false">https://rux.vc/?p=3398</guid>

					<description><![CDATA[<p>For the seasoned Java developer it's very easy to switch to kotlin. Even more, thanks to the great effort of JetBrains team for java interop, there is no need to wait for the greenfield project to start to write kotlin code. You can start koding straight away by either implementing new functionality in kotlin or ... <a title="Functional kotlin part 1: safe calls" class="read-more" href="https://rux.vc/2019.09/functional-kotlin-part-1-nullable-safe-calls/" aria-label="More on Functional kotlin part 1: safe calls">Read more</a></p>
The post <a href="https://rux.vc/2019.09/functional-kotlin-part-1-nullable-safe-calls/">Functional kotlin part 1: safe calls</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></description>
										<content:encoded><![CDATA[<p>For the seasoned Java <g class="gr_ gr_11 gr-alert gr_gramm gr_inline_cards gr_run_anim Punctuation only-ins replaceWithoutSep" id="11" data-gr-id="11">developer</g> it's very easy to switch to kotlin. Even more, thanks to the great effort of <g class="gr_ gr_10 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins replaceWithoutSep" id="10" data-gr-id="10">JetBrains</g> team for java interop, there is no need to wait for the greenfield project to start to write kotlin code. You can start <g class="gr_ gr_5 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="5" data-gr-id="5">koding</g> straight away by either implementing new functionality in kotlin or converting existing classes into the new language by employing Intellj Idea automagic converter</p>



<p>This is a first of this series of posts unioned by tag <a href="https://rux.vc/tags/kotlin-showoff/">#kotlin-showoff</a></p>



<span id="more-3398"></span>



<p>As from my experience it takes literally two days for average developer to switch to kotlin from java and start to write meaningful business logic</p>



<p>As time goes by code can use more kotlin specific constructions which make code much more readable and expressive. In this blog post I'd like to show off some of the nice functional constructions which help to make code more idiomatic.</p>



<h3 class="wp-block-heading">Extracting data from the nullable types</h3>



<p>Say, we have an class <code>Address</code> within <code>UserInfo</code> which holds information about the given user's address. <code>UserInfo</code> is a part of the <code>Person</code>. <code>UserInfo</code> can be nullalbe as well as <code>Address</code> but we want to extract city name. In java it would look like:</p>



<pre class="wp-block-prismatic-blocks"><code class="language-java">    Person person;
    String city;
    if (person.userInfo != null &amp;&amp; person.userInfo.address != null &amp;&amp; person.userInfo.address.city != null)
        city = person.userInfo.address.city;
    else city = &quot;Unknown city&quot;;

    System.out.println(&quot;User is in &quot; + city);
</code></pre>



<p>If you think it's a safe code I have <g class="gr_ gr_19 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar multiReplace" id="19" data-gr-id="19">a bad news</g> for you. Savvy java developer can immediately spot the issue - between checks and <g class="gr_ gr_8 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="8" data-gr-id="8">assigment</g> to <g class="gr_ gr_6 gr-alert gr_gramm gr_inline_cards gr_run_anim Style multiReplace" id="6" data-gr-id="6">the </g><code>city</code><g class="gr_ gr_6 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Style multiReplace" id="6" data-gr-id="6"> whole</g> bunch of things can happen on another threads and eventually we can end up with <g class="gr_ gr_9 gr-alert gr_gramm gr_inline_cards gr_run_anim Style multiReplace" id="9" data-gr-id="9"><g class="gr_ gr_5 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar multiReplace" id="5" data-gr-id="5">accessing</g> </g><code>null</code><g class="gr_ gr_9 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Style multiReplace" id="9" data-gr-id="9">.</g> Hello <strong>NPE!</strong></p>



<p>The correct approach would be to <strong>capture</strong> values while we're performing the check:</p>



<pre class="wp-block-prismatic-blocks"><code class="language-java">    UserInfo userInfo = person.userInfo;
    if (userInfo != null) {
        Address address = userInfo.address;
        if (address != null) {
            city = address.city;
        }
    }
    if (city == null) 
        city = &quot;Unknown city&quot;;

    System.out.println(&quot;User is in &quot; + city);
</code></pre>



<p>Expressivity is not Java best strength. But wait, with Java 8 we can make it a <strong>bit</strong> more readable (and still safe):</p>



<pre class="wp-block-prismatic-blocks"><code class="language-java">    city = Optional.ofNullable(person.userInfo)
            .map(userInfo -&gt; userInfo.address)
            .map(address -&gt; address.city)
            .orElse(&quot;Unknown city&quot;);

    System.out.println(&quot;User is in &quot; + city);</code></pre>



<p>Looks better, isn't it? Wait for kotlin</p>



<pre class="wp-block-code"><code>println(&quot;User is in ${person.userInfo?.address?.city ?: &quot;Unknown city&quot;}&quot;)</code></pre>



<p><strong>Sorry java ¯\_(ツ)_/¯</strong></p>



<p>So what exactly happens here? The <g class="gr_ gr_9 gr-alert gr_gramm gr_inline_cards gr_run_anim Style multiReplace" id="9" data-gr-id="9">chain </g><code>person.userInfo?.address?.city</code><g class="gr_ gr_9 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Style multiReplace" id="9" data-gr-id="9"> returns</g> either city if it's <g class="gr_ gr_10 gr-alert gr_gramm gr_inline_cards gr_run_anim Style multiReplace" id="10" data-gr-id="10">not </g><code>null</code><g class="gr_ gr_10 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Style multiReplace" id="10" data-gr-id="10"> </g><g class="gr_ gr_12 gr-alert gr_gramm gr_inline_cards gr_run_anim Style multiReplace" id="12" data-gr-id="12"><g class="gr_ gr_10 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Style multiReplace" id="10" data-gr-id="10">or</g> </g><code>null</code><g class="gr_ gr_12 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Style multiReplace" id="12" data-gr-id="12">.</g> Then using <g class="gr_ gr_6 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="6" data-gr-id="6">elvis</g> operator we make <g class="gr_ gr_7 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins replaceWithoutSep" id="7" data-gr-id="7">whole</g> expression to return <g class="gr_ gr_11 gr-alert gr_gramm gr_inline_cards gr_run_anim Style multiReplace" id="11" data-gr-id="11">extracted </g><code>city</code><g class="gr_ gr_11 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Style multiReplace" id="11" data-gr-id="11"> value</g> or string "Unknown city". Even more, we can concatenate everything in one string as an expression</p>



<blockquote class="wp-block-quote"><p>You can eat your cake, and have it too</p></blockquote>



<p>Is it safe one might wonder? Yes, it is. Look into the generated code:</p>



<pre class="wp-block-prismatic-blocks"><code class="language-java">public final class KotlinImplKt {
   public static final void kotlinImpl() {
      StringBuilder var10000;
      String var4;
      label14: {
         Person person = new Person();
         var10000 = (new StringBuilder()).append(&quot;User is in &quot;);
         UserInfo var10001 = person.userInfo;
         if (var10001 != null) {
            Address var3 = var10001.address;
            if (var3 != null) {
               var4 = var3.city;
               if (var4 != null) {
                  break label14;
               }
            }
         }

         var4 = &quot;Unknown city&quot;;
      }

      String var1 = var10000.append(var4).toString();
      boolean var2 = false;
      System.out.println(var1);
   }
}
</code></pre>



<p></p>



<p>Check out other posts in <a href="https://rux.vc/tags/kotlin-showoff/">#kotlin-showoff</a></p>The post <a href="https://rux.vc/2019.09/functional-kotlin-part-1-nullable-safe-calls/">Functional kotlin part 1: safe calls</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></content:encoded>
					
					<wfw:commentRss>https://rux.vc/2019.09/functional-kotlin-part-1-nullable-safe-calls/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3398</post-id>	</item>
	</channel>
</rss>
