<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Marcos Sandoval on Medium]]></title>
        <description><![CDATA[Stories by Marcos Sandoval on Medium]]></description>
        <link>https://medium.com/@m.sandovalcalvo?source=rss-d1d0082a2013------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*MYcsBShIgBkZKdak.</url>
            <title>Stories by Marcos Sandoval on Medium</title>
            <link>https://medium.com/@m.sandovalcalvo?source=rss-d1d0082a2013------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 05:50:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@m.sandovalcalvo/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Kotlin type system: Unveiling the mystery]]></title>
            <link>https://medium.com/@m.sandovalcalvo/kotlin-type-system-unveiling-the-mystery-50613f0db893?source=rss-d1d0082a2013------2</link>
            <guid isPermaLink="false">https://medium.com/p/50613f0db893</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Marcos Sandoval]]></dc:creator>
            <pubDate>Wed, 18 Sep 2019 15:11:15 GMT</pubDate>
            <atom:updated>2019-09-18T15:11:15.699Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*54-VzeYJASrIWJDt8SElGw.png" /></figure><h3><strong>What is a type system?</strong></h3><p>Type systems are a set of rules that determine the types of language construct. This set of rules allow us to ensure that all the parts of our program integrate consistently, plus, a clear and robust type system allows the compiler to execute low-level optimizations that improve the code.</p><p>Additionally, a consistent and robust type system should give enough understanding of the business logic and the program in general through, for example, defining the properties of the business’s models.</p><h3><strong>Kotlin type system</strong></h3><p>Kotlin comes along with a very powerful typing system, it was created thinking on making the development process less verbose, more focused on giving value to the business and preventing errors as much as possible. Among the most important characteristics of Kotlin type system we have:</p><ul><li><strong>Nullable types: </strong>They are data types that allow us to keep null values, defining a type as nullable the compiler will run some validations at compile time to ensure a Null Pointer Exception won’t be thrown. Nullability support gives a lot of options to avoid this kind of exceptions and drive them on a very elegant way.</li><li><strong>Type Inference:</strong> When a variable or property is declared and initialized it is not necessary to explicitly indicate its type, Kotlin can infer the data type based on the context.</li><li><strong>Unreachable code analysis:</strong> Based on the type of an expression or the return type of a function the type system can determine when a portion of code is not reachable.</li></ul><h3><strong>What’s a nullable type?</strong></h3><p>Basically a nullable type is any data type which is able to keep null as its value. In Kotlin they are denoted with the symbol ?as a suffix, for instance, String? is a String type which is able to keep a String or null. Although this looks very simple it gives a lot of power to the compiler, specifically to the Type Checker, which can analyze our code and determine when a null value can produce an exception, when the Type Checker detects a nullable property it won’t allow us to use it without having first tested that it is not null</p><h3><strong>Kotlin built-in types</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eKyYD8utOhoeRc1Kf7K1MA.png" /></figure><p>It is important to remember that Kotlin doesn’t have primitive types, all are objects. Besides the types mentioned above, we have “user-defined types” like Classes, Interfaces, and Enums. On the other hand, functions (which can we stored on a variable), the nullable operator (?), and generics are composed types.</p><h3><strong>Kotlin type system hierarchy</strong></h3><p><strong>Supertype: </strong><strong>Any?</strong></p><p>As in Java any class extends from Object class, in Kotlin any non-nullable class extends from Any. Like any other data type of Kotlin, Any has its nullable version which is Any?, Any? is the supertype of Any and also it is the supertype of all the nullable types. Ok, so confusing, right? Let’s recap, since all the non-nullable types extend from Any and Any extends from Any? and, the supertype of all nullable types is Any?<em> </em>we concluded that the supertype of all the Kotlin data types is Any?. This type can be used on code to say that we are accepting any type of value, for instance:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7b1d9197818b1251ef8be4bb809c66f/href">https://medium.com/media/b7b1d9197818b1251ef8be4bb809c66f/href</a></iframe><p><em>printAny</em> is a function that can take any value and print it, for example, it can be used as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42f3e36046f770cb232b2690fa8932b2/href">https://medium.com/media/42f3e36046f770cb232b2690fa8932b2/href</a></iframe><p><strong>Subtype: </strong><strong>Nothing</strong></p><p>At the very bottom of the Kotlin type hierarchy we have Nothing, Nothing extends all the types. In other words, Int, String<em>, </em>and any other Kotlin or custom type is extended by Nothing. But, what is Nothing ? Nothing is a type that has no instances, it represents an expression that can’t be executed (it will always throw an exception) so that an expression of type Nothing doesn’t result in a value and an expression which return type is Nothing never return at all. A function that enters an infinite loop or kills the current process has the result type Nothing. Everything after an expression which type is Nothing is marked as unreachable code. Let’s modify our previous example and make it return Nothing type</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47e8187ab1f5bfb3c6b13aed2d15e385/href">https://medium.com/media/47e8187ab1f5bfb3c6b13aed2d15e385/href</a></iframe><p>If we call the function as we did before all the lines after the first call will be marked as unreachable code since function printAny will never return.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23514ece206dbf4f8549994cb17d2c63/href">https://medium.com/media/23514ece206dbf4f8549994cb17d2c63/href</a></iframe><p><strong>Where is </strong><strong>null on the hierarchy?</strong></p><p>To make it clear, let’s explain it with an example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*ARVhLedh9SOo1osISqRULg.png" /></figure><p>When we declare a property without explicitly indicate its type and assigning null as its value<em>,</em> its type will be determined as Nothing? that’s because this is the data type of null. Null is the only possible instance of Nothing?, there is not an object which type is specifically Nothing?<em>, </em>at code level we can be totally sure that when we see a property which type is Nothing? the only possible value it can keep is null. Also, since Nothing is the subtype of all types, null can be used as the nullable version of any type we declare</p><p>If we need to initialize a property as null but be able to assign it an object later on, we have to indicate its type explicitly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4e26175bc26c20a1f656e3131108dc5/href">https://medium.com/media/f4e26175bc26c20a1f656e3131108dc5/href</a></iframe><p><strong>Unit</strong></p><p>There is nothing special about Unit type, it is another Kotlin type which extends from Any and it is extended by Nothing. When we declare a function and we don’t explicitly declare its return type, the compiler will determinate it as Unit. A function which return type is Unit represents a function that is called for its side effects, that means it will execute some actions and calculations in its scope producing some effects on itself or in any other object, returning a singleton value Unit. Unit return type represents a function that will return the control flow to its caller and allow the program to continue executing, unlike Nothing which is a function that will never return the control to the caller, breaking the flow of the program and preventing its completion.</p><p>For instance</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e708f136f2dd9fa2af9958acbf48f26c/href">https://medium.com/media/e708f136f2dd9fa2af9958acbf48f26c/href</a></iframe><p>This is the same as</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d893b1fef21ea84c1a1d5b71015be104/href">https://medium.com/media/d893b1fef21ea84c1a1d5b71015be104/href</a></iframe><p>But the compiler will warn us that it is redundant to return a Unit and indicate the return type since it can be inferred.</p><p>As we can see below, Unit is an object class that doesn’t have any property, it is more like a wrapper to indicate to the compiler the control flow has been returned to the caller.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pLaV3nnUfgR7NAK_XMLHTw.png" /></figure><p><strong>Generic types are, by default, nullable</strong></p><p>Let’s look at an example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/411ca9a1270ec937cf653c2de46839d3/href">https://medium.com/media/411ca9a1270ec937cf653c2de46839d3/href</a></iframe><p>It is a function that can take any type of value, including null, and print it. It can be used as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69fff62cf2580063d293940bc295d986/href">https://medium.com/media/69fff62cf2580063d293940bc295d986/href</a></iframe><p>If we don’t want to allow null values we need to modify our example as below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2dc23e76b3c2ae231ad97b45b712f1cd/href">https://medium.com/media/2dc23e76b3c2ae231ad97b45b712f1cd/href</a></iframe><p>In this case, we are indicating that we are accepting any type but it should extend from Any, which means, no nullable values are allowed. If we try to call the function passing null it will throw an error since null is an instance of Nothing? and<em> </em><em>Nothing?</em> extends from Any? not from Any.</p><p><strong>Minimum common types</strong></p><p>Since Kotlin executes type inference, sometimes it is difficult to know which is the type of an expression. Let’s look at an example</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/270fd29dffb397cd263d8a38c5deca42/href">https://medium.com/media/270fd29dffb397cd263d8a38c5deca42/href</a></iframe><p>What do you think is the type of value expression? Most of the languages resolve this issue by assigning the “closest” supertype which is common to both types, which is known as “Minimum common type”. So, considering that we can conclude that the type of value is Any<em> </em>because it is the<em> minimum common type </em>between<em> </em><em>String </em>and<em> </em><em>Int</em>, which is correct.</p><p>But, what happens in the case of value2<em>? </em>The common type between Int and Double is Number, so, is Number the type of value2? Wrong, Kotlin doesn’t look for the minimum common type, it will always assign Any on the cases where the type is not clear.</p><p><strong>Let’s summarize with an image</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EfanxY8YrEg4vyq8u8iz7Q.png" /></figure><p>To summarize:</p><ul><li>On the very top of the hierarchy we have Any?, all the classes extend from it by transcendence.</li><li><em>Nothing</em> extends all the classes, including custom classes created by the user, so that it is at the bottom of the hierarchy.</li><li><em>Unit</em> is a Singleton class that, as other Kotlin classes, extends from Any and represents a function that is called for its side effects and doesn’t return a value to the caller.</li><li><em>Unit</em> type returns the control flow to the caller allowing the program to continue executing while Nothing never returns the control to the caller, throwing an exception or stopping the execution of the program by running infinitely.</li><li>When an expression declares Nothing like a return type, everything executed after that will be unreachable.</li><li>When the type of an expression is not totally clear, the type system will set it up as Any? Or Any, depending on the context.</li><li>When a variable is initialized with null and without explicitly declare its type, the type system will determine its type as Nothing?.</li><li>Unlike other languages, Kotlin distincts between classes that can keep null values, called nullable classes, and classes that can’t. Also, Kotlin has very powerful mechanisms to run validations and prevent null pointer exception (NPE).</li><li>Nullable type is a supertype of the non-nullable one.</li><li>Generic classes are nullable by default.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50613f0db893" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LiveData & ViewModel — Making your own magic]]></title>
            <link>https://medium.com/mindorks/livedata-viewmodel-making-your-own-magic-73facb06fbb?source=rss-d1d0082a2013------2</link>
            <guid isPermaLink="false">https://medium.com/p/73facb06fbb</guid>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[android-architecture]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[livedata]]></category>
            <dc:creator><![CDATA[Marcos Sandoval]]></dc:creator>
            <pubDate>Wed, 09 Jan 2019 17:15:18 GMT</pubDate>
            <atom:updated>2019-01-09T17:15:18.597Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qz5XimWSi6bPV6JWGte97A.png" /><figcaption>The rights of this image are for <a href="https://erikcaffrey.github.io/ANDROID-kotlin-arch-components/">erikcaffrey.github.io</a></figcaption></figure><h3>LiveData &amp; ViewModel — Making your own magic</h3><p>User Experience(UX) is probably the most critical part of any product creation. To the final user it doesn’t a matter if you use the best material to build your product or the best algorithms to create your software or if you do it as efficient as possible, if your product doesn’t offer a good experience to the user it won’t use it, that’s simple.</p><p>User experience is composed of a lot of elements, for instance: UI composition, navigation pattern, colors, fonts, data accuracy, etc. On this post we will focus on data accuracy and how Google architectural components can help us to create apps that keep automatically synchronized the UI with the data on the model.</p><h3>LiveData</h3><blockquote>LiveData is an observable data holder class</blockquote><p>As Google defined it, LiveData is a class that has only one property, it allows us to save/hold any object into that property. But LiveData is more than that, it is an observable class, which means it implements the <a href="https://en.wikipedia.org/wiki/Observer_pattern">observable design pattern</a>, which allows us to subscribe entities that will be notified when the data contained on the LiveData class change. But there is one more feature that makes LiveData a very good option to include it on our project. LiveData class is lifecycle-aware, which means it respects and it is aware of the lifecycle state of the observer subscribed to it.</p><blockquote>If you want to learn more about lifecycle-aware components and how to create your own, <a href="https://medium.com/@m.sandovalcalvo/lifecycle-aware-components-with-kotlin-architecture-components-f1da83e59edd">I strongly recommend reading my article about it</a>.</blockquote><p>The reasons to use LiveData can be summarized in the follows:</p><ul><li><strong>Data/UI synchronization:</strong> Because LiveData follows the observable pattern it will notify the UI of any changes, this ensures perfect data synchronization between the two layers without any manual data change verification.</li><li><strong>No more life-cycle related crashes:</strong> Since LiveData is a lifecycle aware component it ensures to remove any lifecycleObserver when its status is destroyed, avoiding memory leaks due to unused/inexistence references. Also, LiveData will only send notification about data change only to the observers that are on an active state like onResume.</li><li><strong>No more manual data update: </strong>Observable pattern allows to avoid manual work to update and synchronize the UI with our data. When a configuration change happens or when it returns from an inactive state to active state it will receive the latest data right after it came back, this happens on the OnCreate when the ViewModelProviders is called, as we will see below</li></ul><h3>ViewModel</h3><p>ViewModel is a helper class which is part of the <a href="https://developer.android.com/topic/libraries/architecture/">Android Architecture Components</a>, it helps us to store, manage and prepare UI related data in a lifecycle conscious way. The main benefit of the ViewModel is that it is created the first time and if the Activity, Fragment or any other LifecycleOwner is destroyed or recreated by the system, the next time it starts it will receive the same ViewModel created before. It works like a Loader (AsyncTaskLoader and CursorLoader)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*HIgh3zkFkGfjIbWcew7ZhQ.png" /><figcaption>ViewModel lifecycle</figcaption></figure><p>As we noticed in the image above, the ViewModel is kept alive even when the Activity is destroyed or reconstructed due to a configuration change for example. When the activity is finished the ViewModel calls the onCleared() method to clean up any remaining resource and avoid memory leaks.</p><p>We must keep in mind:</p><ul><li>A ViewModel class shouldn’t have any reference to LifecycleOwner, like Activity or fragment, or to the context, this makes the unit testing easier</li><li>ViewModel object can contain LifecycleObservers , such as LiveData objects, but a ViewModel must never observe changes to lifecycle-aware observables, this has to be done on the LifecycleOwner</li><li>If the ViewModel needs the Application context it should extend AndroidViewModel and receive the Application on the constructor</li></ul><h3>Ok, let’s check the code</h3><p>For this article, we will continue using the example created for the article about Room I posted some months ago, you can visit and read the article on <a href="https://medium.com/mindorks/room-kotlin-android-architecture-components-71cad5a1bb35">this link</a> to get context about the sample or learn about Room. Also, all the sample codes are written using Kotlin, if you don’t know Kotlin or you want to learn more, I would invite you to <a href="https://medium.com/@m.sandovalcalvo/android-and-kotlin-a-very-promising-relationship-have-started-4950114506a3">visit this link and read my article about it</a>.</p><p>The first thing we need to do is to update our gradle file. It should look like the following</p><p><strong>App.gradle</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fc2a0d1e5583f1f5d12a3fac4745480/href">https://medium.com/media/3fc2a0d1e5583f1f5d12a3fac4745480/href</a></iframe><p>As we mentioned above, ViewModel object can contain LifecycleObservers , such as LiveData object, so that let’s see how do they interact with each other.</p><p><strong>MainViewModel.kt</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9310429f875193c8df70d410e3f50be/href">https://medium.com/media/c9310429f875193c8df70d410e3f50be/href</a></iframe><p>Things to notice here:</p><ul><li>Our custom ViewModel class have to extend from ViewModel.</li><li>The ViewModel class receives only one parameter on the constructor, which is the repository that handles our data. This class is out of the scope of the article but it can be consulted on the repository of this example.</li><li>The class has another property, besides the repository, which is a MutableLiveData object that contains/holds a list of Genders . This means we can subscribe to this property to be aware of its changes and react to them, as we will see below. A LiveData object can hold any type of object, in this case it is declared as Mutable since we want to be able to modify its content.</li><li>Finally, we have a ViewModelFactory which implements ViewModelProvider.Factory interface, this is necessary if you need to pass any parameter to your ViewModel, if not you omit that fragment of code</li></ul><p>Now let&#39;s see how to use our ViewModel</p><p><strong>MainActivity.kt</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8504f33790534390a71f84b66b54e032/href">https://medium.com/media/8504f33790534390a71f84b66b54e032/href</a></iframe><p>What are we doing?</p><ul><li>We are getting an instance of our database.</li><li>Then, we are getting an instance of our ViewModel using the ViewModelProvider, this provider will check if there is an instance of the same class already created if so it will return it, with all the data up-to-date. If a ViewModel has not been created yet, it will be created for us. This ensures each time a configuration change or any similar event happens, we won’t lose the current state of our data nor we will create a new instance of the ViewModel each time.</li><li>Finally, we are subscribing to observe and react properly to any change that occurs to the list of gender store on the ViewModel.</li></ul><p>If you don’t need to pass any parameter to the ViewModel class you can omit the implementation of the ViewModelProvider.Factory interface, as we mentioned before, and the call to get an instance of the ViewModel can be simplified like the following example</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bca23e3b9fcf575609fcd66c72e4092b/href">https://medium.com/media/bca23e3b9fcf575609fcd66c72e4092b/href</a></iframe><p>And that’s it :). We have learned how to start building a Reactive MVVM architecture by using Android Architectural components, we will have a more detailed article about reactive apps very soon.</p><p>Also! The whole code of the project <a href="https://github.com/MarcosSandoval/LiveData-ViewModel">can be found from here</a>. Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73facb06fbb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindorks/livedata-viewmodel-making-your-own-magic-73facb06fbb">LiveData &amp; ViewModel — Making your own magic</a> was originally published in <a href="https://medium.com/mindorks">MindOrks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lifecycle-Aware components with Kotlin - Android Architecture Components]]></title>
            <link>https://medium.com/mindorks/lifecycle-aware-components-with-kotlin-architecture-components-f1da83e59edd?source=rss-d1d0082a2013------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1da83e59edd</guid>
            <category><![CDATA[android-architecture]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[lifecycleaware]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Marcos Sandoval]]></dc:creator>
            <pubDate>Wed, 22 Aug 2018 16:01:01 GMT</pubDate>
            <atom:updated>2018-08-22T16:01:01.404Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*58bfOG5NQQFp1fR8GaG9xg.jpeg" /></figure><h3>Lifecycle-Aware components with Kotlin — Android Architecture Components</h3><p>Every component introduced by Google is intended to be a solution to a bad/not good situation or a performance/code improvement. In this case, we want to discuss all problems that can come if we don’t use the lifecycle of the Android components properly.</p><h3>Which are the problems?</h3><ul><li>You are creating an app that plays video/music streaming from internet, you need the app to start buffering the media since it’s open, but playback until it is fully started. Probably you want to stop the video and buffering if the app is on the background and restart it when it comes up to the foreground. Finally, you need to cancel the playback and buffering when your app is closed and also release all the resources at this time.</li><li>You were asked to develop an app that tracks the user’s location as soon as the user opens your app. Your app has to show the user’s location on the screen if it is on the foreground or to store it in the database if it is not on the foreground. Also, when the app is closed you have to stop tracking the user’s location and release all the resources.</li><li>You have an app that requests and sends information to a server in the background to keep both synchronised. This flow of data should start right after the user opens the app, but we also want to know when the user sends the app to the background, closes it or performs any action on it. This synchronization has to be done at least every 5 minutes, and should be stopped when the app is closed.</li></ul><p>Until now the way to handle this kind of situations is adding operations to the lifecycle callbacks of the dependent component (Activity, Fragment, Service, etc), but this approach ends up in a poor organization of code, it is difficult to maintain and it can generate a bunch of errors.</p><blockquote>Most of the app components that are defined in the Android Framework have lifecycles attached to them. Lifecycles are managed by the operating system or the framework code running in your process. They are core to how Android works and your application must respect them. Not doing so may trigger memory leaks or even application crashes.</blockquote><p>With the knowledge that we have until now, the normal way to handle the cases mentioned above is as follows:</p><p><strong>AuditHelper.kt</strong></p><p>This class is in charge to track any action done on the app, this includes when the app is started, paused and stopped.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6aa8ee0ffccbad1541b60d003174b98/href">https://medium.com/media/c6aa8ee0ffccbad1541b60d003174b98/href</a></iframe><p><strong>MainActivity.kt</strong></p><p>To report the requested actions we need to play with the lifecycle callback of the Activity like shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2887fb23d5e6efa28673c75a1e738ced/href">https://medium.com/media/2887fb23d5e6efa28673c75a1e738ced/href</a></iframe><p>This doesn’t look so bad, but in real apps we will end up with a lot of operation being executed on the callbacks and probably all of them are part of different components (class, service, etc) without any relationship between them. Also, it is completely your responsibility of execute the correspondent operation on the right callback so you release the resources when they are not need and avoid memory leaks or execute the right operation when a specific state is reached. It sounds very prone to errors, right? Well, LifeCycle-Aware components come to the rescue.</p><h3>Lifecycle-Aware components</h3><p>These components, <a href="https://developer.android.com/jetpack/docs/release-notes">officially released on January 22th, 2018</a>, are intended to help handling in a more elegant way the operations that depend on the lifecycle. Lifecycle components react to changes on the lifecycle status of other components that are subscribed to observe, helping us to have better organized code, increasing the modularity, encapsulation and maintainability, and reducing the possibility to introduce errors or memory leaks.</p><p>Lifecycle-Aware components can be any of the following types:</p><ul><li>LifecycleOwner: An interface that represents a class that has Android lifecycle, like Activity, Fragment or Service. Also, it can be implemented in a custom class as we will see below.</li><li>LifecycleObserver: An interface that denotes a class that is observing any state change on the LifecycleOwner it subscribes to observe. Also, LifecycleObserver uses OnLifecycleEvent annotation to subscribe its methods to observe specific component state change.</li></ul><h3>Let’s go to the code</h3><p>We are going to refactor the examples we showed above to make them lifecycle aware.</p><p>Before we start, all the sample codes are written using kotlin, if you don’t know Kotlin or you want to learn more, I would like to invite you to<a href="https://medium.com/@m.sandovalcalvo/android-and-kotlin-a-very-promising-relationship-have-started-4950114506a3"> visit this link and read my article about it</a>. Also, if you want learn about Room, the Android Architecture Components for persistence, and simplify the way of how you interact with SQLite on your apps, I strongly recommend you to visit my article and learn more about this incredible component.</p><p><a href="https://medium.com/@m.sandovalcalvo/room-kotlin-android-architecture-components-71cad5a1bb35">Room - Kotlin, Android Architecture Components</a></p><p>Ok, let’s see the code. The first thing we need to do is to update our gradle file. It should look like the following:</p><p><strong>App.gradle</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cef575b8dbb5c3dc8ae9c931b5d936f5/href">https://medium.com/media/cef575b8dbb5c3dc8ae9c931b5d936f5/href</a></iframe><p>As we mention above, lifecycle aware components can be: LifecycleObserver or LifecycleOwner. Let’s start with our <strong>LifecycleObserver:</strong></p><p><strong>AuditHelperLifecycleAware.kt</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d64e78e469c8748e040df35c80736107/href">https://medium.com/media/d64e78e469c8748e040df35c80736107/href</a></iframe><p>Things to be noticed here:</p><ul><li>We need to implement the LifecycleObserver interface, this marks a class as a LifecycleObserver. It does not have any methods, instead, it relies on OnLifecycleEvent annotated methods.</li><li>We use the annotation @OnLifecycleEvent to indicate that the method needs to be notified when a specific event occurs. For instance, we are indicating we want that the method auditStated() be executed each time the LifecycleOwner, we subscribed to, goes to the state STARTED and so on.</li></ul><p>Now, let’s go the our LifecycleOwner, in this case we are going to use an Activity which extends AppCompatActivity that implements LifecycleOwner interface.</p><p><strong>MainActivityLifecycleAware.kt</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b0576bc88eb5fbdf24cfb97b155fc3f/href">https://medium.com/media/3b0576bc88eb5fbdf24cfb97b155fc3f/href</a></iframe><p>Things to know:</p><ul><li>At the line 9, we are getting the lifecycle of the activity. Since AppCompaqActivity implements LifecycleOwner interface, we can get its lifecycle easier.</li><li>activityLifecycle.addObserver(auditHelper!!) method allows us to indicate we want our AuditHelperLifecycleAware instance to be notified of the state changes of this LifecycleOwner. The parameter addObserver method receives have to be a class that implement LifecycleObserver interface.</li><li>activityLifecycle.addObserver(auditHelper!!) method allows us to indicate we want our AuditHelperLifecycleAware instance to be notified of the state changes of this LifecycleOwner. The parameter that addObserver method receives has to be a class that implements LifecycleObserver interface.</li></ul><p>And that’s it, with a better organized code we are able to be aware of the changes of state of an Activity and react to this changes.</p><p>But hold on, that’s not all. What if I want to have my own LifecycleOwner? Don’t worry, you can do it without write tone of code. Lets see an example:</p><p><strong>CustomLifecycleOwner.kt</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a20ff98eea3d33bdd42fa98f0010d08e/href">https://medium.com/media/a20ff98eea3d33bdd42fa98f0010d08e/href</a></iframe><p>Things to be noticed:</p><ul><li>Our custom lifecycleOwner has to implement the LifecycleOwner interface and implement the method getLifecycle() as shown above.</li><li>lifecycle.markState(state: State) allow us to setup the current state of the class; triggering the lifecycle callbacks so the observers can react to the state changes.</li><li>lifecycle.markState(state: State) allow us to setup the current state of the class; triggering the lifecycle callbacks so the observers can react to the state changes.</li></ul><p>And that’s all. We learned how to create lifecycle aware components, which is the difference between a LifecycleOwner and LifecycleObserver, how to use each of them and how implement our custom LifecycleObserver.</p><p>The whole code of the project<a href="https://github.com/MarcosSandoval/LifecycleAwareComponents"> can be gotten from here</a>. Thanks for reading, if this article was useful or entertaining for you please clap it, share it and follow me. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1da83e59edd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindorks/lifecycle-aware-components-with-kotlin-architecture-components-f1da83e59edd">Lifecycle-Aware components with Kotlin - Android Architecture Components</a> was originally published in <a href="https://medium.com/mindorks">MindOrks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Room - Kotlin, Android Architecture Components]]></title>
            <link>https://medium.com/mindorks/room-kotlin-android-architecture-components-71cad5a1bb35?source=rss-d1d0082a2013------2</link>
            <guid isPermaLink="false">https://medium.com/p/71cad5a1bb35</guid>
            <category><![CDATA[android-architecture]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[room]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mobile]]></category>
            <dc:creator><![CDATA[Marcos Sandoval]]></dc:creator>
            <pubDate>Fri, 03 Aug 2018 16:15:55 GMT</pubDate>
            <atom:updated>2019-09-26T00:36:00.446Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F-AeO9PhHK6kPxlUk1LJ7Q.png" /><figcaption>The rights of this image are for <a href="https://www.raywenderlich.com/">RayWenderLich</a></figcaption></figure><h3>Room — Kotlin, Android Architecture Components</h3><p>When we talk about storing information in a persistent way on Android, the most important and “easy” option is to use plain SQLite, if you do a good implementation, this implies:</p><ol><li>Creating a contract class which contains the constants for the URIs, tables and columns name (which should extends from BaseColumns).</li><li>Creating a class that extends SQLiteOpenHelper which will create the database the first time it is called. To do this, you need to manually create a query string indicating the name of the tables and columns you want to create, using the contract defined on the above step. This is difficult to maintain and can introduce a bunch of errors.</li><li>Once you have created your DB, if you want to insert, update or delete information you have to instantiate your subclass of SQLiteOpenHelper , get a writable version of the DB, also you need to create a ContentValues using the contract class created on the first step, to set the keys and the values with the information you need to save. In the case of update and delete operations, you can also define a projection to select specific information base on the value of a column.</li><li>In the case you want to read information, you have to instantiate your subclass of SQLiteOpenHelper, get a readable version of the DB and create a projection. As a result, you will get a Cursor which then you have to go through, column by column, to get the information you need.</li></ol><p>It sounds like too much work, doesn’t it? If you want to do this easier, you can use an <a href="https://en.wikipedia.org/wiki/Object-relational_mapping">ORM</a> but you still need to manually defined and create the DB, subclassing SQLiteOpenHelper and creating the contract classes. So, the question is: <strong>Is there any way to simplify all this process?</strong>, the answer is:<strong> Yes, Room is your solution.</strong></p><h3><strong>What is Room?</strong></h3><blockquote>The Room persistence library provides an abstraction layer over SQLite to allow for more robust database access while harnessing the full power of SQLite.</blockquote><p>Room is part of the Android Architecture Components presented in the Google I/O 2016. It is not an ORM, it is a whole library that allows us to create and manipulate SQLite databases easier, by using annotations we can define our databases, its tables and operations; Room will automatically translate these annotations into SQLite instructions/queries to perform the correspondent operations into the DB engine.</p><p>Room architecture looks like follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*jT94pc71uD_A2TPN_E2ulg.png" /><figcaption>Room Architecture by Google</figcaption></figure><p>The three major components of Room are:</p><ul><li><strong>Database: </strong>It represents the DB, it is an object that holds a connection to the SQLite DB and all the operations are executed through it. It is annotated with @Database.</li><li><strong>Entity:</strong> Represents a table within the Room Database. It should be annotated with @Entity.</li><li><strong>DAO</strong>: An interface that contains the methods to access the Database. It is annotated with @Dao.</li></ul><h3>Too much talk, let see an example:</h3><p>Let’s imagine that we need to create an app to store your gym routine, we are going to have 4 entities in our database as we’ll show below. All the sample codes are written using kotlin, if you don’t know Kotlin or you want to learn more, I would like to invite you to <a href="https://medium.com/@m.sandovalcalvo/android-and-kotlin-a-very-promising-relationship-have-started-4950114506a3">visit this link and read my article about it</a>.</p><p>The first thing we need to do is to update our gradle file. It should look like the following</p><p><strong>App.gragle</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eedf9d726fe97335cef218df12b4c100/href">https://medium.com/media/eedf9d726fe97335cef218df12b4c100/href</a></iframe><p>As we mentioned, Room is composed of three major components: Entities, DAO’s and DataBase. Let’s see and analyze each of them:</p><h3>Entities</h3><p>For our example we are going to use four entities: Gender, Exercise, Routine and Trainee.</p><p><strong>Gender.kt</strong></p><p>It represents the gender of the trainee.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69dd5a0eb3c5c1fe1e2668e9a82eec4b/href">https://medium.com/media/69dd5a0eb3c5c1fe1e2668e9a82eec4b/href</a></iframe><p>Things to know:</p><ul><li>All the classes that represent an entity of the database have to be annotated with @Entity.</li><li>With the annotation @PrimaryKey(autoGenerate = true) we are indicating that id is the primary key of the entity and should be autoGenerate by the database engine.</li></ul><p><strong>Exercise.kt</strong></p><p>It represents an exercise that it is part of a routine.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db6eb3f127355d11126d05469155ef7c/href">https://medium.com/media/db6eb3f127355d11126d05469155ef7c/href</a></iframe><p>Things to notice:</p><ul><li>By default, Room uses the field names as the column names in the database. If you want a column to have a different name, add the <a href="https://developer.android.com/reference/android/arch/persistence/room/ColumnInfo.html">@ColumnInfo</a> annotation to a field.</li></ul><p><strong>Routine.kt</strong></p><p>It is basically a container of exercises that together create an exercise routine.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fd5c49dd5c67b5a959f6b4d36a33dd8/href">https://medium.com/media/8fd5c49dd5c67b5a959f6b4d36a33dd8/href</a></iframe><p>Things to notice:</p><ul><li>When a class is annotated with @Entity the name of the tablet will be the name of the class, if we want to use a different one we have to add the tableName property along with the @Entity annotation.</li><li>@TypeConverters annotation has to be used when we declare a property which type is a custom class, a list, date type or any other type that Room and SQL don’t know how to serialize. In this case, we are using the annotation at the class field level whereby only that field will be able to use it. Depending on where the annotation is placed it will behave differently as <a href="https://developer.android.com/reference/androidx/room/TypeConverters">explained here</a>.</li></ul><p><strong>Trainee.kt</strong></p><p>It represents the owner of the routine.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/863eacc633671861af09b86b4a304107/href">https://medium.com/media/863eacc633671861af09b86b4a304107/href</a></iframe><p>There are several things to be noticed here:</p><ul><li>The indices property at @Entity annotation is used to index certain fields in the database to speed up the queries. In this case, we are indicating that the columns: nameand age have to be indexed.</li><li>The property called foreignKeys is used to indicate a relationship between two or more tables, it receives an array of ForeignKeys . entity property is the name of the father class, parentColumns is the name of the column at the father class and childColumns is the name of the column at the class where it is used.</li><li>We use @Embedded annotation when we want to represent an object that we’d like to decompose into its subfields within a table. We can, then, query the embedded fields just as you would for other individual columns. This allow us to express an entity or plain old Java object (POJO) as a cohesive whole in our database logic, even if the object contains several fields.</li></ul><h3>DAOs</h3><p>Data Access Objects or DAOs are used to access our data when we implement Room. Each DAO have to include a set of methods to manipulate the data (insert, update, delete or get).</p><p>A DAO can be implemented as an interface or as an abstract class, in our case we are going to use an interface. Due to all the DAOs are basically identical we will show only one.</p><p><strong>GenderDao.kt</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cc2438c632692ec1d664e3903453725/href">https://medium.com/media/3cc2438c632692ec1d664e3903453725/href</a></iframe><p>Some things to notice:</p><ul><li>All the DAOs have to be annotated with @Dao.</li><li>A function annotated with @Insert , @Update or @Deletehave to receive an instance of the desired class as a parameter, which represents the object that we want to insert, update or delete respectively.</li><li>In the case of insert or update operations, we can use the property onConflict to indicate what to do when a conflict performing the operation happens. The strategies available to use are: REPLACE , ABORT , FAIL , IGNORE and ROLLBACK.</li><li>If we want to get specific information from one or more entities we can annotate a function with @Query and provide a SQL script as parameter. Another advantage of use Room is: if the SQL query provided in the annotation is invalid, it will fail on compilation time and not in runtime.</li></ul><h3>Type Converters</h3><p>As we said before, Type Converters are used when we declare a property which Room and SQL don’t know how to serialize. Let’s see an example of how to serialize datedata type.</p><p><strong>DateTypeConverter.kt</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba16725b9b2e9d2e6992e28a42aa6e25/href">https://medium.com/media/ba16725b9b2e9d2e6992e28a42aa6e25/href</a></iframe><h3>DataBase</h3><p>It represents the DB, it holds a connection to the actual SQLite DB.</p><p><strong>AppDatabase.kt</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69db714b282848129e8349e6cab0a233/href">https://medium.com/media/69db714b282848129e8349e6cab0a233/href</a></iframe><p>Things to notice here:</p><ul><li>This is an abstract class that has to extend from RoomDatabase.</li><li>It has to be annotated with @Database, it receives a list of entities with all the classes that compose the database (all these classes have to be annotated with @Entity). We also have to provide a database version.</li><li>We have to declare an abstract function for each of the entities included in the @Database annotation, this function has to return the correspondentDAO (A class annotated with @Dao).</li><li>Finally, we declare a companion object to get static access to the method getAppDataBase which gives us a singleton instance of the database.</li></ul><p><strong>Using the Room database</strong></p><p>Now let’s see a very simple example of how to use the Room database we just created</p><p><strong>MainActivity.kt</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9370ce556abaa61ad3812ed0399bed9/href">https://medium.com/media/c9370ce556abaa61ad3812ed0399bed9/href</a></iframe><p>What are we doing?</p><ul><li>We’re getting the instance of the database and GenderDao.</li><li>We’re creating two Gender instances: Male and Female.</li><li>We’re inserting the two instances created into de DB.</li><li>We’re querying the DB to get all the genders store on it.</li><li>We’re merging the name of all the genders we got from the DB and we’re setting the text of the TextView with that value.</li></ul><p>And that’s it :) This is almost everything you need to know to create and use a Database on Android with Room. The whole code of the project <a href="https://github.com/MarcosSandoval/PersonalRutineApp.git">can be gotten from here</a>. Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71cad5a1bb35" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindorks/room-kotlin-android-architecture-components-71cad5a1bb35">Room - Kotlin, Android Architecture Components</a> was originally published in <a href="https://medium.com/mindorks">MindOrks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android and Kotlin, a very promising relationship have started]]></title>
            <link>https://medium.com/mindorks/android-and-kotlin-a-very-promising-relationship-have-started-4950114506a3?source=rss-d1d0082a2013------2</link>
            <guid isPermaLink="false">https://medium.com/p/4950114506a3</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Marcos Sandoval]]></dc:creator>
            <pubDate>Mon, 09 Jul 2018 22:17:15 GMT</pubDate>
            <atom:updated>2018-08-13T23:57:30.211Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*PG7q_78CFDUWF4Q8z247Lw.png" /></figure><p>Defined by JetBrains guys, its creators, as:</p><blockquote>Statically typed programming language for modern multiplatform applications</blockquote><p>Kotlin is the new official Android development language, it was unveiled on July 2011, officially adopted by Google on the <strong>Google I/O 2017 </strong>and it was included on Android Studio since the version 3.0.</p><blockquote>… Kotlin is expressive, concise, extensible, powerful, and a joy to read and write.</blockquote><p>Created with the idea of eliminate the <strong>boilerplate </strong>code, it includes a bunch of new features to accomplish this goal. <strong>The idea is simple: Do more with less code. But more than this, the main goal of Kotlin, and all modern programming languages (Swift, Go, etc), is to have better code. And when we say “Better code” we are also talking about aspects of the safety, besides others, which allows the programmers to reduce the bugs and whole categories of errors as we will see through the article</strong>.<strong> </strong>Let’s see how Kotlin can become your Android apps development into a new, beautiful and sweet experience</p><h3>Awesome new features</h3><p><strong>Auto-biding views</strong></p><p>Have you ever you Butterknife or findViewById to get references to your views from the activity or fragment?. If so, you don’t need to take of this anymore. Consider the following layout called activity_main.xml</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa23285f3be41f3cf28712e0579f1266/href">https://medium.com/media/aa23285f3be41f3cf28712e0579f1266/href</a></iframe><p>To use any view on the corresponding activity/fragment, you only have to import the layout, let’s see how:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/382895e72420cd0d4279794772f77aeb/href">https://medium.com/media/382895e72420cd0d4279794772f77aeb/href</a></iframe><p><strong>Type Inference</strong></p><p>Let’s see the following code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6083f358197922f0cd461b6d461399d/href">https://medium.com/media/c6083f358197922f0cd461b6d461399d/href</a></iframe><p>At least you don’t initialize the variable at the moment you declare it, you don’t need to explicity declare the data type, Kotlin can infere it. In the case of last variable of the example, the compiler will show a warning saying: “Explicitly given type is redundant here” so you can remove the data type at the declaration. As side note, var reserved word represents a mutable variable while val represents an inmutable variable</p><p><strong>Null Safety</strong></p><p>Have ever have a headache trying to find the cause of a <strong>NullPointerException</strong> error? Fortunately Kotlin introduce null-check at compilation time; which don’t allow you to run code without an initialization since by default all properties and variables on Kotlin are considered <em>not-null </em>(unable to hold a null value)<em>, </em>at least you explicitly declared it null. Let’s analize the following declarations:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32c6cf3824ffa66aaa9102f1e3fd246a/href">https://medium.com/media/32c6cf3824ffa66aaa9102f1e3fd246a/href</a></iframe><p>With a question mark we indicate to the compiler that the variable is able to keep null values. In this way, each time we want to use a variable that can hold null values we have to add a question mark to the statement to indicate to the compiler that the operation on this variable have to be execute <strong>only if the variable is not null</strong>. Let’s see an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa0819a88beec7593397cbc621b551a8/href">https://medium.com/media/fa0819a88beec7593397cbc621b551a8/href</a></iframe><p>In the above sample code, the first time lengthis called it will be executed since stringVariable is not null, however the second call of length won’t be executed by the compiler due to the stringVariable became null.<strong> “?:” </strong>is called<strong> Elvis Operator, </strong>it works in conjunction with null<strong> </strong>checker, in the example we are indicating return 10 if stringVariableis null and length can’t be execute.<strong> </strong>On this way, the nullPointerException is not a problem anymore.</p><p><strong>Lambda Expressions</strong></p><p>The normal way to declare a onClickListener on Android using Java is as follow:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/102e992e3ea1375393b29d0c9e553d3d/href">https://medium.com/media/102e992e3ea1375393b29d0c9e553d3d/href</a></iframe><p>Kotlin allows us to use Lambda expressions, also knows as anonymous functions, to do the same but without too much unnecesary code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/633763c4e07c9503feffdcf68134b204/href">https://medium.com/media/633763c4e07c9503feffdcf68134b204/href</a></iframe><p>Lambda Functions are especially good to work with collections. Imagine you need to go through a list of number and get the add up of all of them, to perform that action you just need a line of code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d84fad61ab5b4505546223e212f65d1/href">https://medium.com/media/4d84fad61ab5b4505546223e212f65d1/href</a></iframe><p>Also, you can store a lambda function into a variable and then use it or pass it as a parameter of another function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bd4c1a40417d7afc505db545bc9508c/href">https://medium.com/media/2bd4c1a40417d7afc505db545bc9508c/href</a></iframe><p><strong>Extension functions</strong></p><p>Extensions functions allow you to add new funcionality to existing classes, without modify the original declaration of the class or extend it. This is very useful when you want to add new behaviour to third party or framework classes that don’t allow you to modify them. For instance:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94e37b3d98147ffd47a52d21f314de3c/href">https://medium.com/media/94e37b3d98147ffd47a52d21f314de3c/href</a></iframe><p>On the example above we are extending the ArrayList class by adding a new function called average(). Now we can use it as any other function of the ArrayList class; this also can be apply to classes created by us. An important detail to keep in mind is that to use an extension outside its declaring package, we need to import it at the call site. Let’s see how to use the extension function created:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8d26ee99ea873864d6891089ec18fe6/href">https://medium.com/media/d8d26ee99ea873864d6891089ec18fe6/href</a></iframe><p><strong><em>with()</em> Function</strong></p><p>Consider the following sample class</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73d087112e1d03b087761e355cbff986/href">https://medium.com/media/73d087112e1d03b087761e355cbff986/href</a></iframe><p>If you need to interact with the class, its properties and method, you can do it without type the name of the variable followed by a period, as follow:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8e39523fcf5f56a5add7f1fce4022ae/href">https://medium.com/media/c8e39523fcf5f56a5add7f1fce4022ae/href</a></iframe><p><strong>High Order Functions</strong></p><p>High Order Functions are those that accept functions as parameters and also allow us return a function. Let’s see an example</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/897b3c524e56cd55d7949f8e7517354a/href">https://medium.com/media/897b3c524e56cd55d7949f8e7517354a/href</a></iframe><p>In the above example we are saying that checkoutOrder function will receive a function called <strong>actionToExecute </strong>as a parameter, <strong>actionToExecute </strong>have to be a function that receives two ints as parameter and doesn’t return nothing. To use this function we can do something like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f00d7e4b048f6873ebea1c7b255f4cae/href">https://medium.com/media/f00d7e4b048f6873ebea1c7b255f4cae/href</a></iframe><p><strong>Data class</strong></p><p>Plain Old Java Object or POJO are commonly use on Android to represent business objects, they are classes that only contain properties, its getter and setter methods, besides other methods like: <em>equals()</em>, <em>toString()</em>, <em>hasCode()</em>, etc. With Kotlin you can create a POJO, its constructor, getter, setter methods and the others helper methods with only one line of code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46f9dc35fbc244ef58d7fcdc219a56e9/href">https://medium.com/media/46f9dc35fbc244ef58d7fcdc219a56e9/href</a></iframe><p>In the above example we are creating a POJO called <em>Book </em>which has three mutable properties: title, author, year; the helper methods: <em>equals()</em>, <em>toString()</em>, <em>hasCode(), getters and setters and constructor </em>are autogenerated by Kotlin.</p><h3>Kotlin notes:</h3><ul><li>As maybe you already noticed, it isn’t necessary to write semicolon at the end of the line to indicate the end of the statement.</li><li>By default everything (variables, constants, functions, classes, etc.) has a public scope.</li><li><em>Var </em>is a reserved word that represents a mutable variable while <em>val </em>indicate an immutable variable.</li><li>Properties on Kotlin must be assigned when declared or in a constructor, at least you declared them as <em>lateinit </em>or add a question mark to allow them keep null values.</li><li>In Kotlin everything extends from Any as in Java everything extends from Object and there are not primitive types.</li><li>By default, classes are final so in order to extend a class it has to be declared as <em>open </em>or <em>abstract.</em></li><li>Unit is the default return value for functions, it is similar to Void in Java.</li><li>The arguments of the function can have defaults values.</li><li>When calling a function the name of the argument can be used to improve the readability of the code.</li><li>If for some crazy reason you want a <em>NullPointerException </em>thrown the same way as in Java, you can use<em> !!</em> operator.</li><li>To perform a cast you have to use the keyword <em>as</em>, but whether you want a “safe” cast with a null validation you can use <em>as? </em>which will return null is the casting is not valid.</li><li>A big difference with Java is the == and != behaves different, in Koltin == and != validate is the value of the properties of two instances are the same, but if you want to compare if the instances of an object are the same (identity check) you need to use === and !==</li></ul><h3>Conclusion</h3><p>Kotlin was created thinking in the developer, providing a more concise, intuitive and readable syntax and allowing the developers create more significant functionality with less code. It’s still a young programming language, but due to it was already officially adopted by Google, it will start to grow from now</p><p>A final comment, a crucial thing to mention is that all aspects of a new language has a place and should not be abused. For instance, the ability to make things more concise should not give the developer license to make things so cryptic as to be unreadable by fellow programmers. Just because one CAN do that now does not mean one should :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4950114506a3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindorks/android-and-kotlin-a-very-promising-relationship-have-started-4950114506a3">Android and Kotlin, a very promising relationship have started</a> was originally published in <a href="https://medium.com/mindorks">MindOrks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>