Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

Android application development with Kotlin: Build Your First Android App In No Time
Android application development with Kotlin: Build Your First Android App In No Time
Android application development with Kotlin: Build Your First Android App In No Time
Ebook717 pages9 hours

Android application development with Kotlin: Build Your First Android App In No Time

Rating: 0 out of 5 stars

()

Read preview

About this ebook

This book aims to provide the knowledge around the fundamental concept of Kotlin languages, and it’s an application in Android application development. It covers basic to advanced concepts with practical examples. Each chapter in this book is a step by step journey towards the learning Kotlin and excel in various topics and concepts. It covers topics like data types, various functions, including lambdas and higher-order functions. It also covers advanced topics like Generics, Collections, DSL, Coroutine, etc. Most importantly, such concepts are explained with practical usage of it in Android application. You will get to know what is the best possible way to use these concepts while you develop an Android application. In this book, along with Kotlin, an attempt has been made where few Android-specific topics are also explained. For example, the application is using Architecture components, including ViewModel, LiveData, NavigationComponent, and also it uses Flow, which is a hot topic in Kotlin. While we learn this concept, along with that, we also develop a sample application where we can apply our learning and, in the end, have some tangible and measurable output.
Readers with little previous knowledge of Android application development can easily follow this book. Most of the chapters are code-heavy and focuses on practical usage of Kotlin’s features. Each chapter has code on the GitHub. You can check out this code and try it out. Or you can develop in parallel and cherry-pick things from the sample code base as and when you need it. Few chapters also follow the quiz at the end, and you can self assess yourself by going through that quiz. In total there are ten chapters.
LanguageEnglish
Release dateMay 12, 2020
ISBN9789389423518
Android application development with Kotlin: Build Your First Android App In No Time

Related to Android application development with Kotlin

Related ebooks

Programming For You

View More

Related articles

Reviews for Android application development with Kotlin

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Android application development with Kotlin - Hardik Trivedi

    CHAPTER 1

    Getting Started with Kotin for Android

    Any fool can write code that a computer can understand. Good programmers write code that humans can understand.

    – Martin Fowler

    Many of us very much believe in the above quote. And might be wondering if the above statement is true why there is no programming language following this quote. With Kotlin your quest will come to an end. Welcome to the world of Kotlin.

    Those who are still new to Kotlin, for them I would describe Kotlin as,

    A modern language to meet the modern age requirements.

    Very expressive and no verbosity.

    A statically typed language with a top-notch type of safety. For example, Null safety.

    And 100% interoperable with Java.

    Kotlin as a language has a plethora of features to offer an abundance of applications. You can completely rely on this language and develop your application in Android, JavaFX, Spring boot, JavaScript, Node.js even iOS and embedded systems.

    Structure

    Setting up an environment for Android app development

    Configure Kotlin and make it run with Android Studio and Gradle

    Hello Kotlin program in Android written in Kotlin

    Brush up on Android basics

    Writing Android applications in Kotlin is pure bliss. And with this, some of the coolest start-ups to Fortune 500 companies will agree. Image Credit - https://developer.android.com/kotlin (Data as on 1st July 2019):

    Figure 1.1

    Kotlin is owned by the IDE (Integrated Development Environment) giant JetBrains s.r.o. They are the best in class as far as IDEs are concerns. And with the above companies using it, you can see that Kotlin is in the safe hands of great open source developers’ community. And it surely has a bright future. Kotlin is free and open-source under the Apache 2.0 license. JetBrains unveiled this project Kotlin back in 2011 and after that hardworking team was working on it to make it robust and rich with features. In February 2016 finally, the team released Kotlin v1.0. This was the first official stable release.

    According to PYPL (PopularitY of Programming Language) index, Kotlin has made it to the top 15 in countries like India, United Kingdom, France, and Germany. And in the United States, it has secured rank 16. (The data has compiled against June 2019 as per http://pypl.github.io/PYPL.html)

    During the annual developer conference, I/O-17 Google has announced its official support to Kotlin. From that day Kotlin has become the official language for Android application development. Google has also promised that for all documentations, tutorials, blogs, and code references on the developer website they are going to prefer Kotlin first. From the day of the announcement and to current day Kotlin has gained so much popularity in the Android developer community. In this chapter, you will soon realize the potential of this language and see how easy it is to start using it with its fantastic tooling support with Android Studio.

    How does the Kotlin code look like?

    In following Figure 1.2, some of the coolest features of Kotlin are highlighted.

    Figure 1.2

    You can see how lambdas are making the callbacks looks natural. Basically whatever you are seeing inside those curly braces is nothing but a function. A function passed as the last parameter can take the form of such curly braces and make the code look natural as if it is executed as a body of launch function.

    Another feature that is emphasized here is named arguments, where you can bind a parameter along with its name at the time of calling it. With named arguments, you can take the liberty of changing order as well. This feature makes a lot of sense when there is a function with a lot of parameters. You can easily understand the parameters and their purpose just by looking at the function call.

    For hardcore Java developer, a de novo feature is string interpolation. It’s a simple feature but incredibly useful when readability comes to a picture. You can easily concatenate strings by using $ sign in double-quotes.

    Last but not least no semicolons (:).

    How does Kotlin build process work with Android?

    If you are a seasoned Android developer who knows about how Android build system works will surely have a question - Do I need to learn anything else as well to make Kotlin work with Android and build an APK file?

    Answer The answer is NO. Just by knowing Koltin is enough. All your knowledge about the build system still stands true. Kotlin is a JVM language, this means if your existing code is working with JVM the Kotlin code will work as well with no changes in your build process. Kotlin’s output is also the bytecode, in short, a .class file. Any JVM can interpret the .class file and can process that and derive the instructions written inside it.

    JetBrains IDE will come with Kotlin’s compiler by default. An IDE will compile your Kotlin code and produce the bytecode. For Android, the Android Studio has first-class support for Kotlin from version 3.0 onwards. Both Dalvik (A just in time compiler) and ART (An ahead of time compiler) can perceive bytecode. So for the Android build system, it doesn’t matter that the code is written on Kotlin or Java. Android doesn’t even know that code is written in which of these languages.

    Refer to below Figure 1.3 to get more clarity around how Kotlin code can be used by Android and have no side effects at all:

    Figure 1.3

    Configure Kotlin in Android Studio

    It was a dream come true for the Android developer community when Google announced the Android Studio as the official IDE for Android application development. It has evolved so beautifully that any feature you can think of or ask is there already. The Android Studio is amazingly customized for the need of the developer community. This makes application development fast and easy.

    When Kotlin was announced as the official language for Android app development, there was no out of the box support for Kotlin. Developers have to perform a few steps to configure Kotlin into their Android project.

    Note: If your Android Studio version is 3.0 or above skip this section. But if your Android Studio version is below 3.0 and does not want to upgrade to version 3.0 or above, you need to follow the below steps.

    Note: If your Android Studio version is 3.0 or above skip this section. But if your Android Studio version is below 3.0 and do not want to upgrade to version 3.0 or above, you need to follow below steps. Installing Android Studio

    Throughout the learning and application development, we will only and only use Android Studio. If you are not having Android Studio on your computer please below steps will help you to get it installed.

    Downloading and installing Java

    Android still relies heavily on Java Development Kit (JDK). Nowadays Android Studio comes with the latest OpenJDK embedded into the installer only to provide a jump start to entry-level developers. But it is always nice to have the latest version of JDK installed. Java has done a few releases in the last 2-3 years. While writing this book the latest release was Java 12. But for Android, it’s recommended to have JDK 8 on your computer. Please download the JDK 8 from link https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

    Follow these instructions to install Java on your Microsoft’s Windows or Apple’s Mac computers, or Linux machines. https://java.com/en/download/help/download_options.xml

    Downloading and installing Android Studio

    Get the latest stable version of Android Studio from https://developer.android.com/studio. The page will automatically detect your OS and suggest either Windows, Linux, or Mac-based installers. Android Studio requires a slightly high configuration compared to standard computers. The above-mentioned page also has a section about system requirements. Please make sure your computer is matching the system requirement to ensure good development and learning experience.

    Google and Android Studio team has done a pretty amazing job right from providing help to install them on any machines. This link https://developer.android.com/studio/install is always up to date with the installation video against the latest releases.

    Just follow the above video and get the Android Studio installed on your machine.

    Installing Kotlin plugin

    Below Android Studio 3.0 the only way to use Kotlin was to install a plugin.

    Go to File | Settings | Plugins | Install JetBrains plugin and search for Kotlin and install it.

    And if you are Welcome to Android Studio screen, choose to Configure | Plugins | Install JetBrains plugin and then search for Kotlin and install it.

    Tip: While installing Android Studio if there is no Android SDK found, the wizard will ask you to install the Android SDK. At this moment you should see two options Standard and Custom. Always select the Standard option if you are unsure and you can always customize it later installation as well.

    After installation Android Studio needs to be restarted. The search plugin window will look like below Figure 1.4:

    Figure 1.4

    Updating build.gradle

    As a next step, we will add classpath and apply plugin into both project and app level build.gradle file.

    Add classpath into the project’s build.gradle

    Add the blow highlighted code as classpath in build.gradle. Whatever defined inside project level build.gradle will be shared by all modules within the project. If it’s a multi module project all project can have Kotlin:

    buildscript {

    ext.kotlinVersion = 1.3.31

    ext.supportLibVersion = 26.0.0

    repositories {

    jcenter()

    }

    dependencies {

    classpath ‘com.android.tools.build:gradle:3.4.1’

    classpath org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion

    classpath org.jetbrains.kotlin:kotlin-android-extensions:$kotlinVersion

    }

    }

    Add Koltin as a library

    After Kotlin defined in the classpath, you need to add Kotlin as a library into app level build.gradle. Add the lines which are highlighted with bold fonts into your app level build.gradle file:

    apply plugin: ‘com.android.application’

    apply plugin: ‘kotlin-android’

    apply plugin: ‘kotlin-android-extensions’

    android {

    // … various gradle setup

    }

    dependencies {

    compile fileTree(dir: ‘libs’, include: [‘*.jar’])

    testCompile ‘junit:junit:4.12’

    compile com.android.support:appcompat-v7:$supportLibVersion

    compile com.android.support:recyclerview-v7:$supportLibVersion

    compile org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version

    }

    If and only if you specify the above code in your build.gradle file will enable you to write Kotlin code in your Android application development.

    Note: Depending upon the version of your Android Studio and your Gradle system you may be prompted to replace compile to implementation.

    Create a new project

    After the installation, plug-in setup you are all set to create a new project and go on expeditions for your Kotlin learning. Adventure, learning, and fun are guaranteed in each and every section now onwards.

    As a part of learning and creating something meaningful, we have selected The recipe app as a project. We will create an app that covers all the scenarios any Android developer can face during their real project work. We will dig down more to understand the scope of this application in the coming chapter. For now, we will just proceed with project creation. We will name our project The International Dhaba:

    Launch Android Studio and you should see something like Figure 1.5:

    Figure 1.5

    Select the type of Activity you need. For now, we will just go ahead with blank activity as an option. We do not need any complicated navigation or interface. See Figure 1.6:

    Figure 1.6

    Configure a project. As a next step enter the project name and select other details exactly like Figure 1.7 as described below. If you are using Android Studio older than version 3 you will not see the language selection option and you need to set up Kotlin manually. Follow the Configure Koltin in Android Studio section:

    Figure 1.7

    Setting up Android emulator

    Now the project has been set up, the next step is to figure out how we will run the Android projects. As an Android developer, you can run your project on both emulator and real device without any trouble. Android SDK will allow to set a variety of emulators to test your application. You can set up emulators based on your requirements, for example, API level, hardware, screen density, memory, storage configuration, network latency, even architecture of your OS. Emulators are a very powerful, robust and efficient way to test your application. Android calls them virtual devices. The developer portal has step by step guide on setting up emulators or AVDs on your computer. Please follow https://developer.android.com/studio/run/managing-avds completely to set up emulators which suits your needs.

    Recommended configurations for this book and project:

    Device: Pixel 3

    OS Android 9 or API level 28

    Screen resolution: 1080 x 2160

    CPU architecture: x86_64

    RAM: 1024 MB

    There will be other details while setting up emulators, for example, Heap size, SD card memory, and more. You can keep as it is.

    Tip: Android emulators are sometimes slow. To get the best performance on an emulator, make sure you select x86 CPU architecture. Also, you should install the Intel x86 Emulator Accelerator (HAXM) on your computer. This will make a visible difference while interacting with an emulator.

    Display Hello Kotlin

    Enough of theory! Where is my Kotlin code? How do I just start writing my Android application in Kotlin? I am sure you want the answer to this question. This section will surely make you happy. In this section, you will get a gist of Kotlin code. You will get that feeling how amazing it is to write an application using Kotlin.

    If you are using Android Studio older than 3.0 you will have MainActivity.java in your src directory under your main package. This means you need to convert this file into Kotlin file to start writing the code.

    To convert the Java code into Kotlin code, Android Studio has in build converter:

    Open MainActivity.java.

    Go to the menu Code.

    Select the Convert Java file to Kotlin file option.

    On successful completion of the above three steps you should have MainActivity.kt and you should see the Kotlin code instead of Java.

    For Android Studio 3.0 and above, after the project setup is completed you will already have MainActivity.kt inside your src directory under your main package.

    Open activity_main.xml from res/layout directory and put below content inside it:

    1.0 encoding=utf-8?>

    xmlns:android=http://schemas.android.com/apk/res/android

    xmlns:app=http://schemas.android.com/apk/res-auto

    android:layout_width=match_parent

    android:layout_height=match_parent>

    android:id=@+id/displayTextView

    android:layout_width=0dp

    android:layout_height=wrap_content

    app:layout_constraintLeft_toLeftOf=parent

    app:layout_constraintRight_toRightOf=parent

    app:layout_constraintTop_toTopOf=parent

    android:layout_marginTop=16dp

    android:layout_marginLeft=16dp

    android:layout_marginRight=16dp/>

    android:text=Click

    android:layout_width=0dp

    android:layout_height=wrap_content

    android:id=@+id/clickButton

    app:layout_constraintTop_toBottomOf=@+id/displayTextView

    android:layout_marginTop=16dp

    app:layout_constraintStart_toStartOf=parent

    android:layout_marginStart=16dp

    app:layout_constraintEnd_toEndOf=parent

    android:layout_marginEnd=16dp/>

    Go to MainActivity.kt file. Here we will do a very ordinary exercise. We will set a click listener on clickButton and try to display Hello Kotlin on displayTextView TextView. The code to achieve this can look like below:

    class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {

    super.onCreate(savedInstanceState)

    setContentView(R.layout.activity_main)

    clickButton.setOnClickListener {

    displayTextView.text=Hello Kotlin

    }

    }

    }

    The highlighted code snippet does the job. Sounds interesting, isn’t it?

    On the other side Java code can be these verbose and full of Android ceremonies:

    public class SplashActivity extends AppCompatActivity {

    private Button buttonClick;

    private TextView displayTextView;

    @Override

    protected void onCreate(@Nullable Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    buttonClick = findViewById(R.id.clickButton);

    displayTextView = findViewById(R.id.displayTextView);

    buttonClick.setOnClickListener(new View.OnClickListener() {

    @Override

    public void onClick(View view) {

    displayTextView.setText(Hello Kotlin);

    }

    });

    }

    }

    Concise and conveying the most this is the motto of Kotlin and they are making it work for this ordinary problem as well.

    Now run the project by clicking on the green play ▶ icon in your Android Studio. Select any of the emulators which you have created before. In a later chapter while we will also learn how to connect and run the application on the real device.

    Understanding the basics of Android

    Android is a highly mature platform. Behind this great platform, there is hard work for some of the greatest engineers and strategists. We presume you have a decent amount of hands-on knowledge around developing an Android application. We will be using some of the very basic Android components and APIs during our learning and throughout this book. Hence it’s important to know them well in advance. In the previous section Display Hello Kotlin we referred the terminology like Activity. The Activity has a very specific meaning in Android. It’s one of the core components provided by the Android platform and through this only you can create any user interactive screen. No user interaction is possible without the Activity in your application.

    I will shed some light on the component we will be using in our application development process.

    Activity

    The significance of Activity in Android application is crucial. It will serve as a gateway to your application. Unlike the traditional programming approach, Android does not have a main method to act as an entry point. It is this Activity which will act as an entry point. After user taps on your application icon on the launcher screen, your application is loaded and Android will look for the Activity you have defined as an entry point of. On finding matching appropriate Activity the UI becomes visible to the user.

    To display any kind of element on screen your class must extend Activity or any valid child of Activity class, that is, FragmentActivity, AppCompatActivity, and more. Technically speaking Activity provides you a window to draw your UI on it. Now your application can have the requirement to show multiple screens, so your application can have multiple activities. Android system is designed in such a way that any application can launch any Activity of any other screen. Having said that this is only possible if a way by application developer itself. For example, you are using WhatsApp and want to store a contact number from which you have just received a message. You tap on Create contact and your phone’s contact screen is opened with some prefilled number. This means your WhatsApp is opening your phone’s create contact Activity.

    Activity lifecycle

    Activity is a special class and component in the Android platform. And the developer has to adhere to some contract to make sure the application and user interface behave expectedly. This contract is known as the Activity lifecycle. I will try to explain some of the very important lifecycle methods which work as a callback to your application. It will announce the important state changes in your view. Hence very important!

    onCreate(): The onCreate() method will be called when Activity is completely created by OS and ready for further input from the user. As a developer, we must override this method. The developer usually creates the view and binds the view element to objects.

    onStart(): When activity about to come to the foreground, the on Start() method is called. This is usually immediately called after on Create(). After this method is called Activity becomes visible to the user.

    onResume(): Finally the activity is fully visible to the user and ready for interaction. Whenever this method is called for any activity this means the activity is on top of the task stack.

    onPause(): Whenever this method is called, it means Activity is partially visible and the user is about to leave that activity.

    onStop(): The reason for onStop() being called is, activity is in the background and no longer visible to the user. When you navigate from one Activity to another Activity, new Activity gets created and your previous Activity goes in onStop mode. You can free up your resources or stop some processes, for example, listening to location, stopping an ongoing network request.

    onDestroy(): This is the final call to your Activity class. This indicates that Activity is about to destroy. OS will free all your resources occupied by the Activity.

    Intent

    Android has components like Activity, Service, Broadcast Receiver, and Content providers. The intent is the message passing mechanism between these components. Imagine where you want to start the Activity and want the Activity to work on some data created by previous Activity. As the name suggests Intent class holds the intent or purpose to start the new Activity or any other component.

    Intent can be of two types, which are explained in the following section.

    Implicit Intent

    For implicit intent, it doesn’t rely on the name of a component to be started. Instead, it depends on the action. Android OS will present all possible components which can handle that intent. Following code demonstrates how you can open an application which is capable to send an email. This code uses concept of implicit intent:

    val emailIntent = Intent(android.content.Intent.ACTION_SEND).apply {

    /* Pass the required data */

    type = plain/text

    putExtra(android.content.Intent.EXTRA_EMAIL, arrayOf(someemailid@whatever.com))

    putExtra(android.content.Intent.EXTRA_SUBJECT, Subject goes here)

    putExtra(android.content.Intent.EXTRA_TEXT, Message goes here)

    }

    /* Pass this action to Android and whichever activity can handle this will respond */

    startActivity(Intent.createChooser(emailIntent, Send an email…))

    Explicit Intent

    As the name suggests, the developer has to specify the name of the component explicitly. You typically use explicit intent in a controlled and know environment (that is, your app) where you know the name of the component.

    Assume you want to start a new Activity called HomeActivity from your current Activity, you can write an explicit intent to start activity like this:

    val intent = Intent(this@SplashActivity, HomeActivity::class.java)

    intent.putExtra(message, Hello from SplashActivity)

    startActivity(intent)

    And SplashActivity can read this message field by getting and unwrapping an intent:

    val message=getIntent().extras.getString(message,No message)

    The getString function for extras object accepts two parameters: A key and a default message. No message will be returned as default message if no value found for key messages.

    Building Intent

    Being a message passing mechanism, it holds certain data so that Android can understand which component to start. To build an Intent you need the following data:

    Component name: Name of a component for example, HomeActivity or SyncService.

    Action: A simple string defined as an action, for example, ACTION_VIEW, ACTION_SEND, and more.

    Data: Data to be processed.

    Category: Category of a component that handles the intent.

    Extras: Additional data in the form of key-value pairs.

    Flag: A Metadata for Android about the launching style of the component. This applies to only the Activity component.

    AndroidManifest.xml

    A must have file for any type of Android application. An android project cannot be built and installed without the AndroidManifest.xml file. It’s the manifesto of your application. This must be named exactly as AndroidManifest.xml. No other name and no other format than XML is allowed. It contains some crucial information like:

    The unique identifier for your application known as a package.

    List of the component which your application supports. You need to register all your activities, services, broadcast receivers, and content providers with their name and all required metadata.

    Type of permission your application can require during runtime.

    Application’s name and icon.

    Supported screen sizes.

    It can look like below:

    1.0 encoding=utf-8?>

    http://schemas.android.com/apk/res/android

    xmlns:tools=http://schemas.android.com/tools

    package=com.hardiktrivedi.theinternationaldhaba>

    android.permission.INTERNET/>

    android.permission.WRITE_EXTERNAL_STORAGE/>

    android:allowBackup=true

    android:icon=@mipmap/ic_launcher

    android:label=@string/app_name

    android:roundIcon=@mipmap/ic_launcher_round

    android:supportsRtl=true

    android:theme=@style/AppTheme

    tools:ignore=GoogleAppIndexingWarning>

    android:name=.SplashActivity

    android:theme=@style/Theme.AppCompat.Light.NoActionBar.FullScreen>

    android.intent.action.MAIN/>

    android.intent.category.LAUNCHER/>

    android:name=preloaded_fonts

    android:resource=@array/preloaded_fonts/>

    Fragment

    Creating an activity is an expensive call to CPU and memory. The biggest advantage with Activity is the life cycle aware view, which leads to substantial control over behavior. So, the Android team thought to define a component that has reusability and has its lifecycle events. This ideology gave birth to Fragment. Fragment is a widely used component now. Each fragment requires an Activity to hold itself. A Fragment can be attached to multiple activities at any given time.

    To create a Fragment you must extend the Fragment class. Then comes the FragmentManager which has sole responsibility to add, replace, or remove from its parent Activity. Like Activity, Fragment also supports back stack navigation. Although managing Fragment’s backstack can be tricky sometimes.

    In most cases, Fragment’s lifecycle is of similar fashion compared to the Activity lifecycle.

    I highly recommend to take a look at https://github.com/xxv/android-lifecycle for utter understanding

    A typical code to add a fragment can be something like:

    val newFragment = ShowRecipeFragment()

    val transaction = supportFragmentManager.beginTransaction()

    transaction.replace(R.id.fragment_container, newFragment)

    transaction.addToBackStack(null)

    transaction.commit()

    And a RecipeFragment view instantiation can look like this:

    class ExampleFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,

        savedInstanceState: Bundle? ): View {

    // Inflate the layout for this fragment

    return inflater.inflate(R.layout.show_recipe_fragment, container, false)

    }

    }

    Context

    Context is one of the most used objects in Android. It’s an abstract term and each of the Android classes (Activity, Service, Application, Broadcast receiver) implements their version of Context. All these different implementations have completely divergent capabilities. Context gives information about the environment under which the application is running. In Android context can be obtained using getApplicationContext(), getContext(), getBaseContext(), or this:

    Table 1.1: Capability of various contexts

    An application can start an Activity from here, but it requires that a new task is created.

    This is legal, but inflation will be done with the default theme for the system on which you are running, not what’s defined in your application.

    Allowed if the receiver is null, which is used for obtaining the current value of a sticky broadcast, on Android 4.2 and above.

    Dave Smith has given a detailed understanding that is shared at https://possiblemobile.com/2013/06/context. Take a good look.

    Trying out Kotlin

    The current stable version for Kotlin, while writing this chapter is v1.3.41. Kotlin’s team offers multiple ways to try out this fantastic language and provide you a jump start to learn this:

    Kotlin is bundled by default with the Intellij IDEA community and ultimate edition.

    Android Studio 3.0 onwards has the full support of Kotlin.

    Eclipse IDE for Java Developers can support Kotlin. For this, you need to download the plugin from the marketplace.

    It also comes with a standalone compiler. Here you can use any text file editor to write the code and build it using the terminal.

    The most recommended way to getting your hands dirty in this language is using the playground on the browser, with no installation and no hassle.

    The browser acts as a sandbox environment to learn Kotlin and provide support to all Kotlin features. Check out the following Figure 1.8 which is browser version of Kotlin playground:

    Figure 1.8

    Wrapping up

    Along with the project set up, we learned some key Android concepts. All the concepts which are highlighted about can have a chapter-long description. They are real bones of Android application development.

    If any of the concepts have made you think more about the behavior and scenarios, take some time and readout on the World Wide Web (WWW). We will use these terminologies and concepts throughout our application writing. The next few chapters will be focusing only and only on Kotlin language’s features only. We learn basics to some of the advanced concepts of Kotlin, including design patterns.

    Throughout this chapter, we praised Kotlin and did all the preparatory work required to learn and practice it. Will it live up to your expectations?

    CHAPTER 2

    Kotlin Fundamentals

    The only way to learn a new programming language is by writing programs in it."

    - Dennis Ritchie

    The chapter exclusively focuses on the fundamentals of the Kotlin language. This covers basic concepts that will enable you to start writing the code in Kotlin. After this chapter, you will have good command on writing code. You will learn each and every topic in detail.

    Structure

    This chapter covers,

    Understanding variables

    Basics about function

    Easy string handling and manipulations

    Controlling program flow

    Handling errors and exceptions

    Playing around functions

    Defining classes and properties

    This chapter would be fun to learn as this covers very light yet important topics. You can practice the code in any of the IDEs, that is, IntelliJ IDEA, Eclipse, Playground on the browser as mentioned in Trying out Kotlin in Chapter 1: Getting started with Kotlin for Android. I would recommend using IntelliJ IDEA (Community edition 2019.1.3) only, throughout this chapter. We will stick to this IDE for a few more chapters. There is no need for any emulator or device to run the program. The console within IntelliJ IDEA is good enough to execute each and every program.

    Let's quickly create a simple project named Kotlin Fundamentals. To create this open IntelliJ IDEA,

    On welcome screen select – Create New Project option.

    Select Kotlin as an option from the left panel:

    Enjoying the preview?
    Page 1 of 1