My First Encounter with Kotlin
Feb 02, 19Synopsis
I have heard a lot about Kotlin in the past but never got an opportunity to work with it on any of my projects. All this changed recently when I started working on a Mobile app centric project. so, I decided to get my hands dirty with Kotlin. I have extensive experience working on Java and have never been convinced to explore functional programming because of my addiction to Java
Introduction
HelloWorld Example
HelloWorld.java
public class HelloWorld {
public static void main(String args[]){
System.out.println("Say Hello");
}
}
HelloWorld.kt
fun main(){
println("Say Hello")
}
Java Bean Example
Employee.java
public class Employee {
private String name;
private String phone;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", phone='" + phone + '\'' +
'}';
}
}
public class HelloWorld {
public static void main(String args[]){
Employee emp = new Employee();
emp.setName("Emp1");
emp.setPhone("222-999-222");
System.out.println("Employee Name is " + emp.getName() + " and Phone No. is " + emp.getPhone());
}
}
Now, the same JavaBean logic in Kotlin
Employee.kt
data class Employee (val name:String, val phone:String)
fun main(){
val emp = Employee("Emp1", "222-999-222")
val(name, phone) = emp
println("Employee Name is $name and Phone No. is $phone")
}
Functions in Kotlin (Equivalent of methods in Java)
fun addNumber(num1: Int, num2: Int): Unit{
println(num1+num2)
}
The return type “Unit” here can be compared to void in Java . Equivalent function with a return type will be as follows
fun addNumber(num1: Int, num2: Int): Int{
return num1 + num2
}
This function makes num3 default value as 20, so num3 becomes an optional parameter in this function
fun addNumber(num1: Int, num2: Int, num3: Int = 20): Int{
return num1 + num2 + num3
}
with named param, We may change the sequence in which parameters are passed E.g. the function above can be called as follows
addNumber(num1=10, num2=30, num3=40)
addNumber(num2=10, num2=30, num1=40)
A Simple class in Kotlin
fun main(){
var hello1 = SimpleClass()
hello1.sayHello()
}
class SimpleClass {
fun sayHello(){
println("Hi")
}
}
or the same class with a constructor parameter
class SimpleClass constructor(var name: String){
fun sayHello(){
println("Hi " + name)
}
}