1
Write a post

Android kotlin: How to (part 1 Class differences)

Published Jun 10, 2017

So recently Google decided to support Kotlin as a secondary language in developing android apps. Though a lot of people had already started hacking their way through with the language due to its reduced syntax, it made android development go on a lot faster.

Moving from java to kotlin is not as easy or as simple as it sounds, though translating your files to kotlin can easy be done with the use of your IDE(studio3.0) but even at that some issues will arise especially at the point where you initialise class variables such as textViews will probably give you an error because of kotlins way of handling uninitialised variables or null types. Here am going to highlight some niffty code changes you should be aware so when you translate those files you can easily debug your errors.

Constructor :

Java ->

final File file = new File(“file.txt”);

Kotlin ->

val file = File(“file.txt”)

Class:

Java ->

public class User {}

Kotlin ->

open class User

Final Attributes:

Java ->

final class User { private final String name; public User(String name) { this.name = name; } public String getName() { return name; } }

Kotlin ->

class User(val name: String)

Primary Constructor:

Same as final attribute;

Interface:

Java ->

public interface Printable { void print();}
public class Document implements Printable { @Override public void print() {
}}

Kotlin ->

interface Printable{ fun print() } class Document : Printable { override fun print() { } }

Abstract Class:

Java ->

public abstract class Document{ public abstract int calculateSize(); } public class Photo extends Document{ @Override public int calculateSize() { }

Kotlin ->

abstract class Document { abstract fun calculateSize(): Int } class Photo : Document() { override fun calculateSize(): Int { } }

Alright those should clear up some beginner confusion, will post some more differences by next week. If any request share on the comment section.

Discover and read more posts from mmumene egbai
get started
Enjoy this post?

Leave a like and comment for mmumene

3
Be the first to share your opinion

Get curated posts in your inbox

Learn programming by reading more posts like this