Codementor Events

Kotlin, What’s going on?

Published Nov 20, 2017

What’s Kotlin?

Kotlin is a new programming language from JetBrains. It first appeared in 2011 when JetBrains unveiled their project named “Kotlin”. Kotlin is an Open-Source Language.

Basically like Java, C and C++ — Kotlin is also “statically typed programming language”. Statically typed programming languages are those languages in which variables need not be defined before they are used. This means that static typing has to do with the explicit declaration or initialization of variables before they are employed.

Benefits of Kotlin Language

  • Kotlin compiles to JVM bytecode or JavaScript  — Like Java, Bytecode is the compiled format for Kotlin programs either. Bytecode means Programming code that, once compiled, is run through a virtual machine instead of the computer’s processor. By using this approach, source code can be run on any platform once it has been compiled and run through the virtual machine. Once a kotlin program has been converted to bytecode, it can be transferred across a network and executed by JVM(Java Virtual Machine).
  • Kotlin is Open Source and it costs nothing to adopt.
  • Kotlin programs can use all existing Java Frameworks and Libraries  — Yes, it’s true that Kotlin programs can use all existing Java frameworks and libraries, even advanced frameworks that rely on annotation processing. The main important thing about Kotlin language is that it can easily integrate with Maven, Gradle and other build systems.
  • Automatic conversion of Java to Kotlin  — JetBrains integrated a new feature into IntelliJ which converts Java to Kotlin and saves a huge amount of time. And it also saves us to retype mundane code.
  • Kotlin can be learned easily and it is approachable. It can be learned easily by simply reading the language reference.The syntax is clean and intuitive(easy to use and understand). Kotlin looks a lot like Scala but is simpler.

Main features from Kotlin

Obviously, Kotlin has a huge of other important features, but, I want to mention the main features that I’ve seen from my researching.

Extension function:
As it’s name indicate this adds some extra feature to the existing component.
Have a look below we are adding an extra feature to integer value which multiplies the number with 4.

fun Int.multi() = this * 4
20.multi()

This will print 80 as a result, what has been done here is when any integer call the method multi () it will multiply that integer with 5 and return the computed result.
Now suppose you want to append some String to an specified String .

fun String.greet():String { return this.plus("you're welcome to our amazing team!")}
"Falcon".greet()

This will print Falcon you’re welcome to our amazing team! as you can see in this example we are using explicit return call when method is surrounded by braces.

Inter-operable with java
What makes kotlin more interesting is that whatever extra advantage that you have in kotlin it can be used directly in your Java code also. If you want to use kotlin class in your java class then just create the object for that class as you normally create in java thereafter start using it.

class Demo{
fun Int.mul() = this * 10
fun String.greet():String { return this.plus(" we welcome you!") }
fun addValue(operation:(Int,Int) -> Int):Int { return operation(10,20) }
fun callThis():Int { return addValue{a,b -> a * b} }}

The above functions are defined inside a kotlin class Demo so in order to use this class in java file create an object for this class and start using these functions.

public class MainActivity extends AppCompatActivity {
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
Demo demo = new Demo(); Log.v("Number:",""+demo.callThis()); Log.v("Number:",""+demo.greet("Jack")); Log.v("Number:",""+demo.mul(25)); }}

High order function
High order function means that if your function accepts function as a parameter or returns function as a result, then, it’s called high order function. What you generally see are first order function who accepts any parameter except function and also return anything except function. Let’s see a simple example on how to use this feature:

fun addValue(operation:(Int,Int) -> Int):Int { return operation(10,20)}
addValue{num1,num2 -> num1 * num2} //This will print 200addValue{num1,num2 -> num1 - num2} //This will print -10

This is very basic example of high order function which accepts function as a parameter, here operation is a keyword which distinguishes that it’s a part of function where you have to define the type of parameter and the return type for that function.

Smart cast
It’s quite the best feature that you can ask for, what this does is that it check for some type and it will allow to perform all the operation allowed for that particular type like for example if the type is string it will allow copy, length etc operation and on the same object. If it detects it’s an integer then it will allow operation done on integer. How do we do that? so for that just use an operator is to check for the type

val n:Any = "Hello"when(n) { is String -> n.length is Int -> n.inc()}

When is just like a switch statement but it can take any type of value.

Note: smart casts do not work when the compiler cannot guarantee about the variable change between the check and the usage.

Smart cast works on the following scenarios if

  • val is local variable
  • val is private or internal

Null safety
The billion dollar mistake null pointer exception can easily be avoided with kotlin using  ?. operator. The way it works is that it first check for the value if is it null or not if it’s not null then only it perform the next action for example.

val str:String = "name"str = null // As str is defined as null save it will show errorstr.length

By default all the object are null safe so they will not accept null as a value but there are scenarios where the value could be null so for those cases explicitly you need to define them but adding ? after its type.

val str:String? = "name"str = nullstr.length //This will show error as ?. is not used may result in NPE.
str?.length //This is completely valid now.
str!!.length //This will produce NPE if str is null.

Multi-value return from function
This kind of scenario comes often where more than one value need to be returned form the function so with Kotlin it’s possible to do. This is actually called as destructuring declaration.

data class Student(val name:String, val age:Int)
fun studentsFun(student: Student):Student { return Student(student.name, student.age)}
val stud = Student("Jhon",24)val (name,age) = ch(stud)println(name)println(age)

Data class
It’s most common in java to create a model class with the getters and setters and in case the type of data member get changed or new member is added than that creates a bit of extra work for the developer. Also sometime model class gets huge to get maintained well enough for any further changes so now all those effort in java is being drop down to a single line in kotlin just add data in front of class and that will become a model class no need for any getters and setters you can directly access the member itself.

public class Student { private String name; private int age;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }}

This model class in java is same as following model in kotlin

data class Student(internal val name:String, internal val age:Int)

No more findViewById()
Kotlin team has also created an extension by using which there will not be any need to use findViewById() instead the id defined in the xml will act as an object name in java or kotlin file. Add the following line to your file over class name

import kotlinx.android.synthetic.main.activity_main.*
public class MainActivity extends AppCompatActivity {
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
Checking checking = new Checking(); tvValue.setText(String.valueOf(checking.callThis())); }}

If you have observe than with import at the end activity_main.* is written well it’s because the xml name here is activity_main so change that with the name of your xml.

Default and named arguments

In Kotlin, you can provide default values to parameters in function definition.

If the function is called with arguments passed, those arguments are used as parameters. However, if the function is called without passing argument(s), default argument are used.

Here, only one (first) argument is passed to the foo() function. Hence, the first argument uses the value passed to the function. However, second argument numberwill take the default value since the second argument is not passed during function call.

The value of letter and number will be 'y' and 15 respectively inside the foo() function.

Here, the foo() function is called without passing any argument. Hence, both arguments uses its default values.

The value of letter and number will be 'a' and 15 respectively inside the foo() function.

  • Versatile

Conclusion

Overall, I’m motivated with Kotlin, it’s a language with a sintax so easy to learn it. In addition, it has incorporated hottest features as optionals, lambas, data class, etc. I hope that you’ve enjoyed this tutorial, for the Ninja Devs Team is a HUGE pleasure can help you.

See you next time!!!!!

Discover and read more posts from Gerardo Lopez Falcon
get started
post commentsBe the first to share your opinion
Show more replies