Thread: Hopping Islands: From Java to Kotlin Part 1

Results 1 to 5 of 5
  1. #1 Hopping Islands: From Java to Kotlin Part 1 
    nbness2#5894

    nbness2's Avatar
    Join Date
    Aug 2011
    Posts
    626
    Thanks given
    238
    Thanks received
    113
    Rep Power
    256
    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
    Code:
    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.
    Code:
    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.

    Code:
    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 let's remove the type.
    var myString = "myString"

    It compiles! But... where's the type? Kotlin compiler uses something called Type inference. Once a variable is initialized without an explicit 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.
    Code:
    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" // 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
    Code:
    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?
    Wrong!
    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. 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 Java's 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.
    Code:
    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) {
            this.name = name;
            this.email = customerEmail;
            this.id = customerId;
        }
    
        public String getName() {
            return name;
        }
    
        public String getEmployeeEmail() {
            return email;
        }
    
        public int getEmployeeId() {
            return id;
        }
    
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Employee employee = (Employee) o;
            return id == employee.id &&
                    Objects.equals(name, employee.name) &&
                    Objects.equals(email, employee.email);
        }
    
        @Override
        public int hashCode() {
            return Objects.hash(name, email, id);
        }
    
        @Override
        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. 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
    Code:
    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);
            System.out.println(myJemployee.getName());
            System.out.println(myKemployee.getName());
        }
    }
    Wait, we never defined getName in 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
    Code:
    fun main() {
        val jEmployee = JEmployee("Jane Doe", "[email protected]", 1)
        val kEmployee = KEmployee("John Doe", "[email protected]", 2)
        println(jEmployee.name)
        println(kEmployee.name)
    }
    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 jEmployee.name = "Mike Hawk"

    If you want custom getters and setters in kotlin, TOO BAD!
    Just kidding. Here's how!
    Code:
    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
    KT/JAVA - NBX 637 - [Only registered and activated users can see links. ]!
    KT - Drop tables made Easy and Readable - [Only registered and activated users can see links. ]!
    KT - Item Containers made Safe, Easy and Powerful - 2019/05/04 UPDATED V2 - [Only registered and activated users can see links. ]
    KT - Utils to make your life easier - [Only registered and activated users can see links. ]
    KT - Hopping Islands: From Java to Kotlin - [Only registered and activated users can see links. ] - [Only registered and activated users can see links. ] - [Only registered and activated users can see links. ]
    Reply With Quote  
     

  2. Thankful user:


  3. #2  
    Registered Member
    Greg's Avatar
    Join Date
    Jun 2010
    Posts
    1,008
    Thanks given
    165
    Thanks received
    460
    Rep Power
    738
    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  
     

  4. #3  
    nbness2#5894

    nbness2's Avatar
    Join Date
    Aug 2011
    Posts
    626
    Thanks given
    238
    Thanks received
    113
    Rep Power
    256
    Updated this post to include the new inline code tag, will be slowly updating my more recent relevant posts with it as well!

    What's the inline code tag? The inline code tag is a code that is very similar to the code block tag [code]code here[/c​ode], but you can do it in the same line without making a lot of space for potentially a very small amount of text. Here's an example of some inline code.

    An inline function to print "Hello inline code!": fun helloInline() = println("Hello inline code!)

    Here's how you use inline code tag: [inline]inline code here[/i​nline] -> inline code here
    KT/JAVA - NBX 637 - [Only registered and activated users can see links. ]!
    KT - Drop tables made Easy and Readable - [Only registered and activated users can see links. ]!
    KT - Item Containers made Safe, Easy and Powerful - 2019/05/04 UPDATED V2 - [Only registered and activated users can see links. ]
    KT - Utils to make your life easier - [Only registered and activated users can see links. ]
    KT - Hopping Islands: From Java to Kotlin - [Only registered and activated users can see links. ] - [Only registered and activated users can see links. ] - [Only registered and activated users can see links. ]
    Reply With Quote  
     

  5. #4  
    Registered Member Andrew's Avatar
    Join Date
    Nov 2008
    Posts
    2,885
    Thanks given
    600
    Thanks received
    196
    Rep Power
    490
    What kind of application are you using Kotlin for?
    This is a lol





    [Only registered and activated users can see links. ]
    Reply With Quote  
     

  6. #5  
    Website Developer

    Sapphira's Avatar
    Join Date
    Mar 2018
    Posts
    63
    Thanks given
    61
    Thanks received
    51
    Rep Power
    110
    this is such a nice contribution/tutorial and i wished more people would have noticed it
    [Only registered and activated users can see links. ]

    [Only registered and activated users can see links. ]

    Syntax is easy. Math is hard.
    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
  •