Thread: Hopping Islands: From Java to Kotlin Part 1

Results 1 to 2 of 2
  1. #1 Hopping Islands: From Java to Kotlin Part 1 

    nbness2's Avatar
    Join Date
    Aug 2011
    Thanks given
    Thanks received
    Rep Power
    Hopping Islands: From Java to Kotlin Part 1.

    This series is aimed at existing Java developers that might feel tempted to switch over. The goal of this series is to introduce Kotlin as a language you can use in tandem with Java, or even as a complete replacement. Across the series, I will be covering a multitude of topics (usually with a few topics per part) on the benefits of using Kotlin over Java. Here are the topics I have picked out for this part:
    • Good day, world!
    • Ceremony free
    • Cross Compatibility
    • Boilerplate free

    Good day, world!
    As is tradition, you absolutely MUST write a hello world program when you start learning a new language. Otherwise, can you ever really say you've learned it?

    Here's a Good day world in Java
    package GoodDay;
    public class GoodDay {
        public static void main(String[] args) {
            System.out.println("Good day, World!");
    All we care about here is the main function (method for you oldies) and the 1 line in it, so why do we need 7?
    Well, using kotlin you can cut this down to exactly that.
    fun main() {
        println("Good day, World!")
    Straight to the point, exactly what you want and exactly what you expect. No need to wonder what's in the System namespace or what out is when all you wanted to do was print "Good day, World!"
    If you want, you CAN add args in to the main method if you want to call it with arguments from outside. But in Kotlin, it's not a necessity.

    fun main(args: Array<String>) {
        println("Good day, ${args[0]}!")
    Note the ${args[0]} inside the string. This is called String Interpolation.
    To interpolate the toString() result of a variable in a string, you put $varName if you want a simple variable in there or ${expression} if you want a more complex expression in there like a function call.

    No ceremony!
    You might've noticed in the Good day, we didn't need to wrap the main function in a class. Why would we, really? It's ceremony (irrelevant stuff you can almost always ignore) for the human's mind to parse, just to get to the one thing that you care about that does anything, the print statement.
    The stuff on screen that actually serves a purpose is called Business Logic. And Kotlin is all about business logic, the good good, the nitty gritty.
    In Kotlin, we can put stuff on the top level, the top level being where there's no indentation (where you put the public class GoodDay in the java file).
    Being able to put more stuff on the top level and not directly inside a class is a really great feature for organization.
    You can put some stuff in package.file1.kt, other stuff in package.file2.kt, and the top level of both will both be accessible through the package namespace!

    Another ceremonious feature that has been removed is typing out the type. In almost every case when you look at an initialized and assigned variable, you can know exactly what it's going to be.
    So... Kotlin removes the need for the unnecessary stuff.
    Here's how you initialize a variable in Java
    String myString = "myString";
    and here's how you would do it in Kotlin
    var myString: String = "myString"
    It's obvious to see that myString is a string, so why don't we just remove the type?
    var myString = "myString"
    It compiles! But... where's the type? It's there, I promise! Kotlin compiler uses something called Type inference. Once a variable is initialized without a type, it is given the type of whatever it was initialized to and you can't change from that. So, this code wouldn't compile.
    var myString = "myString"
    myString = "also myString"
    myString = 1 // The integer literal does not conform to the expected type String.
    There is a god, he just knows that you don't need to be extremely verbose.
    What about variables you don't want changed?
    Well, here's how you would do it in Java
    final String myString = "myString";
    In kotlin
    val myString = "myString"
    myString = "also myString" // Val cannot be reassigned
    You may have noticed that the Kotlin code has no semicolons where you would normally find them in Java.
    Well, you don't really need them. They're at the end of nearly every line anyway, so just remove them.

    Okay... What about Static??
    In Java
    public class ClassName {
        public static final int variableName = 5;
    Now in Kotlin
    val variableName = 5
    No need to type the word static ever again.

    Another ceremonious feature that is now optional is wrapping functions in curly braces!
    fun add(first: Int, second: Int): Int { return first + second }
    Surely that's as simple as it gets, right?
    snaps fingers
    fun add(first: Int, second: Int) = first + second
    You can assign a function directly to an expression.
    You may be wondering where the return type is. DEAD! Just kidding. Type inference!
    Type inference with functions only works with single expression equal assigned functions.
    If no type is assigned to a "regularly typed" function, the return type will be Unit (Kotlin equivalent of void, except it's also an object).

    Cross compatibility!
    Kotlin was designed from the start to be 100% cross compatible. That means you can create a class in Kotlin that inherits from interfaces defined in Java.
    You can call all of the previous Kotlin code from Java, and all of the previous Java code from Kotlin. You can even call Kotlin from Java from Kotlin! The hole goes as deep as you want it to.
    This also enables developers to incrementally convert their code to Kotlin without needing to switch to a new runtime or make any huge architectural adjustments to facilitate a new language.
    The boilerplate section will show the basics of using cross compatibility win Java and Kotlin.

    No more boilerplate!
    Another big feature of Kotlin is boilerplate elimination.
    The biggest examples of boilerplate code that can get tedious to manage and modify is getVariable(), setVariable(), equals(), hashCode() and toString()
    I'd make a guess that these functions are the bulk of boilerplate removed when going from Java to Kotlin.
    import java.util.Objects;
    public class Jemployee {
        private final String name;
        private final String email;
        private final int id;
        Jemployee(String name, String customerEmail, int customerId) {
   = name;
   = customerEmail;
   = customerId;
        public String getName() {
            return name;
        public String getEmployeeEmail() {
            return email;
        public int getEmployeeId() {
            return id;
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Employee employee = (Employee) o;
            return id == &&
                    Objects.equals(name, &&
        public int hashCode() {
            return Objects.hash(name, email, id);
        public String toString() {
            return "Employee{" +
                    "name='" + name + '\'' +
                    ", email='" + email + '\'' +
                    ", id=" + id +
    A lot for your brain to parse, right? And imagine the pain of re generating a new hashCode, newString and equals every single time you wanted to add or remove a field from Employee?

    Well, Kotlin has the class for you. The Data class, that is.
    Here's the equivalent kotlin code
    data class KEmployee(val name: String, val email: String, val id: Int)
    That's it. Seriously. They both do the exact same thing. The difference being one takes 57 lines of code a pain, the other is 1 line of code and a breeze.
    Personal opinion time: The Kotlin version looks a lot easier to maintain and change.

    Here's how you would access these both from Java
    public class Main {
        public static void main(String[] args) {
            final JEmployee myJemployee = new JEmployee("Jane Doe", "[email protected]", 1);
            final KEmployee myKemployee = new KEmployee("John Doe", "[email protected]", 2);
    Wait, we never defined getName KEmployee, wtf?
    That's the great thing about Kotlin, it generates these automatically for you to use from Java!
    A variable declared as a val in Kotlin will only generate getVariable() for Java, while a var will also generate a setVariable()

    And here's how you would access them both from Kotlin
    fun main() {
        val jEmployee = JEmployee("Jane Doe", "[email protected]", 1)
        val kEmployee = KEmployee("John Doe", "[email protected]", 2)
    Hold up... but in Java the variable is private, why can you access it directly in Kotlin?
    Hold your horses! Your stuff is private and you can still use getName(), the kotlin compiler just allows you to use this alternative property access syntax rather than getter and setter methods.
    It should go without saying, but if the variable is a val, you can't use = "Mike Hawk"

    If you want custom getters and setters in kotlin, TOO BAD!
    Just kidding. Here's how!
    class Human(val name: String, val birthDate: Date) {
        val daysAlive: Int
            get() = calculateDaysFrom(birthDate)
    And that's it. You access it from kotlin using Human.daysAlive, or from java using Human.getDaysAlive()

    Hope you found Part 1 of Hopping Islands: From Java to Kotlin useful. Part 2 coming soon
    Discord: nbness2#5894
    Python Framework (???): [Only registered and activated users can see links. ]!
    NBX: [Only registered and activated users can see links. ]!
    DropTable DSL: [Only registered and activated users can see links. ]!
    Make your Inventory easier and safer to work with. Introducing Container: [Only registered and activated users can see links. ]
    Reply With Quote  

  2. #2  
    Registered Member
    Greg's Avatar
    Join Date
    Jun 2010
    Thanks given
    Thanks received
    Rep Power
    This is a sin! You can't have a hello world program say "Good day, world!" that's preposterous!

    Other than that good guides as always
    Reply With Quote  

Thread Information
Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Replies: 1
    Last Post: 04-11-2015, 11:42 AM
  2. Replies: 22
    Last Post: 08-24-2012, 04:33 PM
  3. From .class to .java.
    By Xot Tzox in forum Requests
    Replies: 9
    Last Post: 07-26-2009, 11:04 AM
  4. Changing from Normal to FullScreen
    By 007 Snoop in forum Tutorials
    Replies: 13
    Last Post: 02-16-2008, 01:12 PM
  5. Replies: 3
    Last Post: 07-11-2007, 12:52 AM
Tags for this Thread

View Tag Cloud

Posting Permissions
  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts