• Skip to main content
  • Skip to secondary menu
  • Skip to primary sidebar
  • Skip to footer
  • Articles
  • News
  • Events
  • Advertize
  • Jobs
  • Courses
  • Contact
  • (0)
  • LoginRegister
    • Facebook
    • LinkedIn
    • RSS
      Articles
      News
      Events
      Job Posts
    • Twitter
Datafloq

Datafloq

Data and Technology Insights

  • Categories
    • Big Data
    • Blockchain
    • Cloud
    • Internet Of Things
    • Metaverse
    • Robotics
    • Cybersecurity
    • Startups
    • Strategy
    • Technical
  • Big Data
  • Blockchain
  • Cloud
  • Metaverse
  • Internet Of Things
  • Robotics
  • Cybersecurity
  • Startups
  • Strategy
  • Technical

Enhancing your Development with Kotlin

Rosina De Palma / 6 min read.
May 20, 2019
Datafloq AI Score
×

Datafloq AI Score: 80

Datafloq enables anyone to contribute articles, but we value high-quality content. This means that we do not accept SEO link building content, spammy articles, clickbait, articles written by bots and especially not misinformation. Therefore, we have developed an AI, built using multiple built open-source and proprietary tools to instantly define whether an article is written by a human or a bot and determine the level of bias, objectivity, whether it is fact-based or not, sentiment and overall quality.

Articles published on Datafloq need to have a minimum AI score of 60% and we provide this graph to give more detailed information on how we rate this article. Please note that this is a work in progress and if you have any suggestions, feel free to contact us.

floq.to/8gVsQ

Right since it was announced in Google IO 17, Kotlin has been a big hit among developers and many are now switching their development from traditional Java to Kotlin. My aim is that after reading this article you start using Kotlin for your daily tasks or wherever you have been using Java. So let’s start!

(Note we might cover some core Java concepts in this article)

With help from a big community of developers, Kotlin was developed by JetBrains, which is a software tooling company, as an open source project. So if someone asks you, what is Kotlin, you’d say just like Java it is a statically typed language for computational purposes while supporting both functional programming and object-oriented programming paradigms.
Being said that it’s statically typed, you can omit types in Kotlin, making it look concise as some dynamically-typed languages.

Talking not Kotlin and not talking about interoperability won’t be fair. Kotlin is cent percent interoperable with Java, and we will see that later. You must know that Kotlin is not only for JVM or Android development, you can also compile Kotlin code to JavaScript or even to native code. So you can also do server side and frontend development in Kotlin. Community plays an important role in developing this pragmatic language and you can check this initiative called KEEP (Kotlin Evolution and Enhancement Process).

Kotlin and Java

If you are a Java developer then it is really easy to start with Kotlin. Kotlin supports all existing Java libraries and frameworks. Also, since it’s 100% interoperable you can even mix Kotlin and Java code in one project.

Kotlin code is directly compiled to the Java bytecode, and you can use some tools that automatically convert your Java code to Kotlin code, and this comes handy when you are adding Kotlin to your existing Java project. Let’s now see some Kotlin code in action.

So, we have a simple data class in Java which looks like this –

public class News {

private String title;

public News(String title) {
this.title = title;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}
}

In Kotlin this becomes –

class News(val title: String)

Much more simple and concise ;]

Under the hood, the class looks the same and behave the same at the bytecode level similar to it’s Java analogue. Moreover, if you add the data modifier to this class it will generate some additional useful methods like equals, toString, and hashCode. Let’s now create an object of this class –

In Java –

News news = new News("Kotlin Example");
System.out.println(news.getTitle());

In Kotlin –

val news = News("Kotlin Example");
println(news.title);

Note that we don’t need a new keyword in Kotlin and you call the constructor just like a regular function.

Let’s look at another example –

public void funAge(int age){
String description;
Color color;
if (age < 18){
description = "teenager";
color = BLUE;
}
else if(age > 18){
description = "adolescent";
color = ORANGE;
}
else {
description = "old";
color = RED;
}
}

A simple method that takes age as an argument and update values of description and color. If you use automatic code converter it will look like this In Kotlin –

fun funAge(age: Int){
val description: String
val color: Color
if (age < 18){
description = "teenager"
color = BLUE
}
else if(age > 18){
description = "adolescent"
color = ORANGE
}
else {
description = "old"
color = RED
}
}

But we can improve it using the power of Kotlin! You can see the description variable is repeated several times and we can avoid it by using the Pair class that represents a generic pair of two values –


Interested in what the future will bring? Download our 2023 Technology Trends eBook for free.

Consent

fun funAge(age: Int){
val (description: String, color: Color)=
if (age < 18){
Pair("teenager",BLUE)
}
else if(age > 18){
Pair("adolescent",ORANGE)
}
else {
Pair("old",RED)
}
}

So we initialize two variables at once. As discussed above we can also omit types when the context is clear so you can write this as

fun funAge(age: Int){
val (description, color)=
// ..
}

The compiler will infer the types for us.

Also in Kotlin, there is something called as when expression, which is kind of analogous to switch, allowing you to enumerate several options. There is also a to, which converts a tuple of type Pair(from docs). So now our code becomes –

fun funAge(age: Int){
val (description,color)= when{
age < 18 -> "teenager" to BLUE
age > 18 -> "adolescent" to ORANGE
else -> "old" to RED
}
}

So the Java to Kotlin converter might not always produce the idiomatic Kotlin code and you’ll have to manually improve it. In Kotlin we also have `in` and it is used for iteration and for checking the `belonging`, that is, if certain key belongs to a range or not.

Let’s now look at a simple HelloWorld Kotlin program –

fun main(args: Array<String>){
val name = if (args.size > 0) args[0] else "World"
println("Hello, $name!")
}

The program outputs Hello, World! If no arguments are passed. In Kotlin, you no longer need to put everything inside a class! Also, note that in Kotlin, `if` is an expression. So you can assign that to a variable or return it from a function. Kotlin also provides you with String templates, in which you can pass the value of a variable or also pass complex expression like a function call. Kotlin has two main keywords to define variables,

  • val – this is a `read-only` variable and you can think of it as a final variable in Java as it can’t be reassigned.
  • var – this is a mutable variable which you can reassign.

Another advantage of Kotlin is that you can define functions in every scope, so

  • At the top level –

fun topLevel() = 1

  • Member function at the class level –

class Example {
fun member() = 2
}

  • Local function at the class level –

fun member() {
fun local() = 3

Let’s now look a sample code and see what it prints –

println(listOf('a', 'b', 'c').joinToString(
separator = "", prefix = "(", postfix = ")"))

As you might have guessed we join the contents of the list and it outputs –

(abc)

In this code snippet, we have used the concept of named arguments. So we can specify the name of arguments directly in the code. In Java, you need to explicitly type the overloaded versions of a method, but in Kotlin you can use this feature directly.

Now let’s talk a bit about Exceptions. Kotlin doesn’t differentiate between checked and unchecked exceptions, and handling an exception is a personal choice. Also, it is not mandatory for your function to specify the exception it can throw! So, no more Null Pointers now ;]

Also throw, is an expression in Kotlin, and you can assign the result of `throw` to a variable.

Similarly try is also an expression, and you can again assign the result to a variable.

There are some things in Kotlin which are not analogous to Java. Extension functions extend the class. It is defined outside of the class but can be called as a regular member of the class. Though extension function in by default visible in the whole project and you need to import it explicitly.

On the root, Kotlin Standard Library is just Java Standard Library plus extensions, and that provides very smooth interoperability between Java and Kotlin. So I highly recommend using Kotlin to develop apps.

Kotlin also provides support to lamdas. Lambdas is an anonymous function that can be used as an expression and can be passed as an argument to another function invocation.

With Android Studio 3.0 you can now choose to support Kotlin and you can get started with Kotlin samples in the Google Codelabs. Kotlin is not a purely functional language and with OOP design you are also using the function paradigms of this language. There is a nice section that describes as to why Kotlin was officially supported in Android. Check it here.

Categories: Technical
Tags: application, development, mobile, Programming Language

About Rosina De Palma

Mobile apps developer and technical writer at Nex Mobility for more than 7 years. I have a professional development team for Xamarin, Android and iOS apps. We are also providing best outsourcing services and give end to end solution of aaps programming.

Primary Sidebar

E-mail Newsletter

Sign up to receive email updates daily and to hear what's going on with us!

Publish
AN Article
Submit
a press release
List
AN Event
Create
A Job Post

Related Articles

What is Enterprise Application Integration (EAI), and How Should Your Company Approach It?

March 29, 2023 By Terry Wilson

Technology for Marketing, Singapore

March 29, 2023 By r.chan

eCommerce Expo, Singapore

March 29, 2023 By r.chan

Related Jobs

  • Software Engineer | South Yorkshire, GB - February 07, 2023
  • Software Engineer with C# .net Investment House | London, GB - February 07, 2023
  • Senior Java Developer | London, GB - February 07, 2023
  • Software Engineer – Growing Digital Media Company | London, GB - February 07, 2023
  • LBG Returners – Senior Data Analyst | Chester Moor, GB - February 07, 2023
More Jobs

Tags

AI Amazon analysis analytics app application Artificial Intelligence BI Big Data blockchain business China Cloud Companies company costs crypto customers Data development digital environment experience finance future Google+ government information learning machine learning market mobile Musk news public research security share social social media software startup strategy technology twitter

Related Events

  • 6th Middle East Banking AI & Analytics Summit 2023 | Riyadh, Saudi Arabia - May 10, 2023
  • Data Science Salon NYC: AI & Machine Learning in Finance & Technology | The Theater Center - December 7, 2022
  • Big Data LDN 2023 | Olympia London - September 20, 2023
More events

Related Online Courses

  • Big Data & AI World, Singapore
  • Velocity Data and Analytics Summit, UAE
  • Big Data – Capstone Project
More courses

Footer


Datafloq is the one-stop source for big data, blockchain and artificial intelligence. We offer information, insights and opportunities to drive innovation with emerging technologies.

  • Facebook
  • LinkedIn
  • RSS
  • Twitter

Recent

  • How to Validate OpenAI GPT Model Performance with Text Summarization (Part 1)
  • What is Enterprise Application Integration (EAI), and How Should Your Company Approach It?
  • 5 Best Data Engineering Projects & Ideas for Beginners
  • Personalization Vs. Hyper-Personalization: Benefits, Limitations and Potential
  • Explaining data products lifecycle and their scope in management

Search

Tags

AI Amazon analysis analytics app application Artificial Intelligence BI Big Data blockchain business China Cloud Companies company costs crypto customers Data development digital environment experience finance future Google+ government information learning machine learning market mobile Musk news public research security share social social media software startup strategy technology twitter

Copyright © 2023 Datafloq
HTML Sitemap| Privacy| Terms| Cookies

  • Facebook
  • Twitter
  • LinkedIn
  • WhatsApp

In order to optimize the website and to continuously improve Datafloq, we use cookies. For more information click here.

settings

Dear visitor,
Thank you for visiting Datafloq. If you find our content interesting, please subscribe to our weekly newsletter:

Did you know that you can publish job posts for free on Datafloq? You can start immediately and find the best candidates for free! Click here to get started.

Not Now Subscribe

Thanks for visiting Datafloq
If you enjoyed our content on emerging technologies, why not subscribe to our weekly newsletter to receive the latest news straight into your mailbox?

Subscribe

No thanks

Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

If you disable this cookie, we will not be able to save your preferences. This means that every time you visit this website you will need to enable or disable cookies again.

Marketing cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.

Please enable Strictly Necessary Cookies first so that we can save your preferences!