Calling all JAVA devssteemCreated with Sketch.

in #programming7 years ago

Java vs. Kotlin: Should You Be Using Kotlin for Android Development?

When you think about Android development, chances are one programming language immediately springs to mind: Java.

While it’s true that the majority of Android apps are written in Java, when it comes to Android development, Java isn’t your only option.

You can write Android apps in any language that can compile and run on the Java Virtual Machine (JVM), and your end users will be none the wiser. And one JVM-compatible programming language that’s really caught the attention of the Android community is Kotlin, a statically typed programming language from JetBrains.

If you’ve heard good things about Kotlin and are interested in trying it for yourself, then you're in the right place. In this three-part series, I’m going to share everything you need to know in order to start using Kotlin for Android development.

In this first installment, I'll look at why you, as an Android developer, might want to consider making the switch from Java in the first place, and then I'll examine the pros and cons of selecting Kotlin as your Java replacement. By the end of this article, you'll have a solid grasp of exactly what Kotlin has to offer and will know whether it's right for you.

In part two, we'll be looking at how to set up your Android Studio installation to support Kotlin and create a simple Android app that's written entirely in Kotlin. With these foundations in place, in the third installment we'll look at how to supercharge your Android development, using some more advanced features of the Kotlin language.

Why Should I Make the Switch From Java?
While Java is one of the world's most widely used programming languages and is pretty much the official language of Android development, there are many reasons why Java might not always be the best option for your Android projects.

The biggest issue is that Java isn’t a modern language, and although Java 8 was a huge step forward for the platform, introducing lots of features that developers had been waiting for (including lambda functions), at the time of writing Android only supports a subset of Java 8 features. It seems unlikely that Android developers will be reaping the full benefits of Java 8 anytime soon, so for the foreseeable future if you want to use Java in your Android projects, then you’re pretty much stuck with Java 7.

Java as a whole also has some pretty well-documented language issues, including endless try-catch blocks, a lack of extendability, null-unsafety (and that infamous NullPointerException), not to mention a lack of support for functional programming features. Although Java is starting to add some functional programming elements, such as lambda expressions and functional interfaces, at its core Java is still a procedural language. Java’s syntax is also pretty verbose, particularly when compared to many modern programming languages.

Advantages of Kotlin
So you may want to consider switching to one of the many modern programming languages that are designed to run on the JVM. While there’s no shortage of languages that compile to Java bytecode, there are a few factors that make Kotlin stand out from the crowd:

Interchangeability With Java

One of Kotlin’s greatest strengths as a potential alternative to Java is the sheer level of interoperability between Java and Kotlin—you can even have Java and Kotlin code existing side by side in the same project, and everything will still compile perfectly. Below, you can see an example of a project that consists of a Java Activity and a Kotlin Activity.

A project consisting of a Kotlin Activity and a Java Activity

In fact, once your mixed Kotlin and Java project is compiled, users won’t be able to tell which parts of your project are written in Java, and which parts are written in Kotlin.

Since Kotlin and Java classes can exist side by side in the same project, you can start using Kotlin without having to do anything drastic like converting an entire project to Kotlin or starting a new project specifically so that you can try your hand at Kotlin.

Thanks to this level of interoperability, if you do have a project that you’re already working on, you can trial Kotlin in a small part of that project without affecting the rest of your code base. And, if you do decide that you want to continue using Kotlin, you can either migrate your project’s existing Java code to Kotlin one file at a time, or leave your project's legacy Java code untouched and only use Kotlin for the new classes and features.

Since Kotlin is completely interoperable with Java, you’ll also be able to use the majority of Java libraries and frameworks in your Kotlin projects—even advanced frameworks that rely on annotation processing.

Easy Learning Curve

Kotlin aims to be an enhancement to Java, rather than a complete rewrite, so many of the skills you've acquired and honed throughout your Java career should still be applicable to your Kotlin projects.

Kotlin is also designed to have a gentle learning curve for Java developers. Java developers should find that most of the Kotlin syntax feels familiar; for example, the code that's used to create a new class in Kotlin is very similar to Java:

1
class MainActivity : AppCompatActivity() {
Kotlin is also designed to be intuitive and easy to read, so even if you do encounter some code that's drastically different, you should still be able to get the gist of what this code is doing.

Combine the Best of Functional and Procedural Programming

There are currently a number of programming paradigms that are in widespread use, but when it comes to the question of “which approach is the best”, there’s no easy answer. Each programming paradigm has its own set of strengths and weaknesses, so while there’s no shortage of scenarios where functional programming has an advantage, there are also plenty of problems where a procedural approach is more effective.

So why should you have to choose between functional and procedural? Like many modern programming languages, Kotlin aims to bring you the best of both worlds by combining concepts and elements from both procedural and functional programming.

First-Class Android Studio Support

Kotlin is developed by JetBrains, the company behind IntelliJ—the IDE that Android Studio is based on. It’s no surprise, then, that Android Studio has excellent support for Kotlin. Once you've installed the Kotlin plugin, Android Studio makes configuring Kotlin in your project as straightforward as opening a few menus.

You can configure your project to use Kotlin with just a few mouse clicks

Once you’ve set up the Kotlin plugin for Android Studio, your IDE will have no problem understanding, compiling, and running Kotlin code. Android Studio also provides debugging, auto-completion, code navigation, unit testing, and full refactoring support for Kotlin.

Once your Android Studio project is configured to support Kotlin, you’ll even be able to convert an entire Java source file into a Kotlin file, with just a few clicks of your mouse.

More Concise Code

If you compare a Java class and a Kotlin class that produce the same results, the one written in Kotlin will typically be much more succinct and compact than the one written in Java. And as every developer knows, less code means less bugs!

For example, the following Java code creates an Activity consisting of a floating action button (FAB) that, when tapped, displays a snackbar containing the helpful message This is a snackbar.

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

   FloatingActionButton myfab = (FloatingActionButton) findViewById(R.id.myfab);
   myfab.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View view) {
           Snackbar.make(view, "This is a snackbar", Snackbar.LENGTH_LONG)
                   .setAction("Action", null).show();
       }
   });

}

}
The Kotlin equivalent achieves this same work in less code, particularly when it comes to creating the FAB and setting the onClickListener:

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)

   val myfab = findViewById(R.id.myfab) as FloatingActionButton
   myfab.setOnClickListener { view ->
       Snackbar.make(view, "This is a snackbar", Snackbar.LENGTH_LONG)
               .setAction("Action", null).show()
   }

}

}
Both code snippets have exactly the same output:

An example of a simple Android app that can be written in Java or Kotlin

Kotlin is particularly good at reducing the amount of boilerplate code you need to write, which should make coding in Kotlin a much more enjoyable experience, compared to coding in more verbose languages such as Java.

In particular, Kotlin Android extensions (which we’ll be exploring in part two) allow you to import the reference to a View into an Activity file, so you can then work with the View as though it’s part of that Activity. This means you no longer have to identify each View using findViewById, which can transform code such as:

1
TextView text = (TextView) findViewById(R.id.myTextView); text.setText("Hello World");
Into the much more succinct:

1
myTextView.setText("Hello World")
What's the Catch?
No programming language is perfect, so although Kotlin has lots to offer Android developers, there are some drawbacks you'll need to keep in mind:

Extra Runtime Size

The Kotlin Standard Library and runtime will increase the size of your .apk. While this only equates to around 800KB, if your application is already on the large side then that extra 800KB may tip it over the edge and make users think twice before downloading your app.

Initial Readability of Code

Although Kotlin’s concise syntax is one of the language's greatest strengths, you may initially find some Kotlin difficult to decipher, simply because there’s so much going on in such a small amount of code. Java may be more verbose, but the upside is that everything is clearly spelled out, which means unfamiliar Java code tends to be easier to decipher than unfamiliar Kotlin.

Also, if used incorrectly, Kotlin’s operator overloading can result in code that’s difficult to read.

Lack of Official Support

Kotlin may have excellent support in Android Studio, but it’s worth remembering that Kotlin isn’t officially endorsed by Google.

Also, Android Studio’s auto-complete and compilation tends to run slightly slower when you’re working with Kotlin, compared to a pure Java project.

Smaller Community and Less Available Help

Since Kotlin is a relatively new language, the Kotlin community is still fairly small, particularly compared to the community surrounding more established languages like Java. If you do make the switch to Kotlin, then you may not have access to the same number of tutorials, blog posts, and user documentation, and may encounter less community support on places like forums and Stack Overflow. At the time of writing, searching for Kotlin on Stack Overflow returns just over 4,600 posts tagged with Kotlin—compared to the whopping 1,000,000+ posts that contain the Java tag.

Conclusion

In the first post of this three-part series, we looked at why you may want to consider switching the Java portion of your Android development to one of the more modern, JVM-compatible languages. We also took a closer look at the unique advantages and disadvantages of Kotlin as a potential Java replacement.

If you’ve weighed up the pros and cons and have decided to take Kotlin for a spin, then in part two of this series, I'll be showing you how to use Android Studio to create a simple Android app, written entirely in Kotlin. We'll also be looking at how you can use Kotlin to make sure you never have to write another findViewById again!

In the meantime, check out some of our other tutorials on Android development here on Envato Tuts+!

Copied article from:https://code.tutsplus.com/articles/java-vs-kotlin-should-you-be-using-kotlin-for-android-development--cms-278

Thanks for reading