This article shows you how to use Kotlin language for Development of Android application.

This article shows you how to use Kotlin language for Development of Android application.

The Android team announced during Google I/O 2017 that Kotlin is now an official language to develop Android Apps.

This means that, while it’s still possible to develop Android Apps using Java, from now on Kotlin is fully supported and Google will make sure that all new Android features, the framework, the IDE and all their libraries work seamlessly with the new language.

Kotlin is a JVM based language developed by JetBrains?, a company known for creating IntelliJ IDEA, a powerful IDE for Java development. Android Studio, the official Android IDE, is based on IntelliJ.

Kotin is Open Source Project primarily under Apache 2 Library.Which promotes developer ecosystem to be united and contibute more freely.

Setting up Your Environment

By default, Android Studio has no idea what to do with Kotlin, so the first step is to install the Kotlin plugin and configure Kotlin in your project.

Installing the Kotlin Plugin

Go to Android Studio\Preferences and select the Plugins entry.

On the Plugins screen, click on Install JetBrains plugin


Configure Kotlin in Project

Now the IDE knows what to do with Kotlin, but your project app doesn’t, so your next move is to modify the project’s build configuration.

Go to Tools\Kotlin\Configure Kotlin in Project.

Why kotlin is more powerful then java?

  • kotlin is more flexible then java.
  • kotlin is Expressive and concise.
  • In the less amount of code you can get output where compare to java you need to write large of code to express the same thing.

Example:To create a class you need to write below code in java:

public class Student{
public String name;
 public String url;

 public String  getName(){
 return name;
 }
 public void  setName(String name){
  this.name=name;
 }
  public String  getUrl(){
 return url;
 }
 public void  setUrl(String url){
  this.url=url;
 }
 @Override 
 public String toString(){
 
 return "Student{" +"name=" +name+",lastname='"+name+ '}'}
}

With kotlin ,you just need to make use of data class.

data class Student(
 var name:String,
 var lastname:String)

This data class auto-generates all the fields and property accessors, as well as some useful methods such as toString(). You also get equals() and hashCode() for free, which are very verbose and can be dangerous if they are incorrectly implemented.

Immutable

One big concern developers need to have when developing multithreaded applications is state management. If a variable is mutable, it can be changed by any thread that can access it. This means that if the data might be changed by multiple sources, you need to manually implement synchronization, which avoids data corruption but increases code complexity and execution time. If the data can never be changed, it can be accessed by multiple threads without error, since the data is immutable.

In Kotlin, you can declare variables with the keywords var and val. The former declares a variable that can be reassigned; the latter a variable that once assigned can never change. This gives the developer and the compiler confidence that the variable cannot be reassigned. Java has similar functionality with the final keyword, but the var/val keywords carry more meaning. When used to declare properties, var defines one with a getter and setter, whereas val defines a property with a getter and a private setter, and it must be assigned in the constructor.

This is not true immutability. If you have a val variable holding a mutable object, say an ArrayList, the contents of the list can be changed, even though you cannot assign a new list to the same variable directly.

Nullability: NO More null pointer exceptions

Kotlin is null-safe because the type explicitly defines whether an object can be null by using the safe call operator (written ?). If you need a variable to hold a null value, you have to declare the type as nullable, adding a question mark after the type.

var nonNullable: String = "My string" // needs to be initialized

var nullable: String?

High-order functions

A higher-order function is a function that takes functions as parameters, or returns a function.

Lambda Expressions

A lambda expression or an anonymous function is a "function literal", i.e. a function that is not declared, but passed immediately as an expression.

String Templates

Kotlin has an awesome feature called string templates that allows strings to contain template expressions.

A string template expression starts with a dollar sign $. Here are few examples:

fun main(args: Array<String>) {

    val myInt = 5;
    val myString = "myInt = $myInt"

    println(myString)
}

When you run the program, the output will be : myInt = 5

It is because the expression $myInt (expression starting with $ sign) inside the string is evaluated and concatenated into the string.

Interoperability

Kotin and Java are Interoperable

Interoperable means you can use both java and kotlin in same project.The android apps can be built on kotlin along with using java and c++.

In Android Studio 3.0, open a Java file and select Code > Convert Java File to Kotlin File.

Or, create a new Kotlin file (File > New > Kotlin File/Class), and then paste your Java code into that file—when prompted, click Yes to convert the code to Kotlin. You can check Don't show this dialog next time, which makes it easy to dump Java code snippets into your Kotlin files.

Example:

create a java class

public class Alien(){
var name;
  //to assign value in java we used getter setter
  create getter setter
  }

we can access or assign the value to above java class from kotiln class

fun main(args:Array<Strings>){

var object=Alien();
//to assign the value to name variable simple donobject.name="rohan";//to get above value 
  println("name ${object.name}")

}

First Program Hello World :

In Java we write are all the code within the class but in kotlin we define the function.

Main method

JAVA:

public class MyClass {
    public static void main(String... args) {
        // code goes here;
    }
}

KOTLIN:

fun main(args :Array<Strings>){
println("Hello World")
}

fun->function name

Arry<String> ->Array of strings.In case of kotlin we define Varibale name first followed by Data type.

In kotlin we used return type as followed:

fun main(args :Array<Strings>):Unit{
println("Hello")
}

Unit stands for void in kotlin .

In java the .java file is converted in class file. Same in kotlin .kt file in converted into class file.

Declaring variables and constants

In kotlin we used var keyword to define variable and val keyword of constant .

val (Immutable reference) - The variable declared using val keyword cannot be changed once the value is assigned. It is similar to final variable in Java.

var (Mutable reference) The variable declared using var keyword can be changed later in the program. It corresponds to regular Java variable.

JAVA:

private String s1 = "my string 1";
private final String s2 = "my string 2";
private static final String s3 = "my string 3";

Kotlin:

var s1 = "my string 1"
val s2 = "my string 2"
val s3 = """my string 3"""

Example:

fun main(args :Array<Strings>){
  var  number=10  //The datatype become integervar  number=1.0 //The datatype become Floting value

    var name : String
You can declare value to above string anywhere as the above string is mutable       in nature.
  
     name="Hello"
  
If you want to fix the value of the above string make the string immutable by using the keyword val.
  
  val name : String
  
  name="Hello"      //Constant value  
  name="My String" //Gives error 
   
}

Kotlin Basic Types

The built-in types in Kotlin can be categorized as:

-Numbers
-Characters
-Booleans
-Arrays

Kotlin Keywords

Keywords are predefined, reserved words used in Kotlin programming that have special meanings to the compiler. These words cannot be used as an identifier.

Kotlin Identifiers

Identifiers are the name given to variables, classes, methods etc. For example:

var salary = 7789.3

Here, var is a keyword, and salary is the name given to the variable (identifier).

Here are the rules and conventions for naming a variable (identifier) in Kotlin:

  • An identifier starts with a letter or underscore followed by zero, letter and digits.
  • Whitespaces are not allowed.
  • An identifier cannot contain symbols such as @, # etc.
  • Identifiers are case sensitive.
  • When creating variables, choose a name that makes sense. For example, score, number, level makes more sense than variable name such as s, n, and l although they valid.
  • If you choose a variable name having more than one word, use all lowercase letters for the first word and capitalize the first letter of each subsequent word. For example, speedLimit.

Kotlin Operators

Operators are special symbols (characters) that carry out operations on operands (variables and values). For example, + is an operator that performs addition.

  • Assignment Operator
  • Unary prefix and Increment/Decrement
  • Comparison and Equality Operators
  • Logical Operators
  • in Operators
  • Index Access Operators
  • Invoke Operator
  • In Operators

The in operator is used to check whether an object belongs to a collection.

Operator 	Expression 	 Translates to
in 	         a in b 	 b.contains(a)
!in 	         a !in b         !b.contains(a)

Example: in Operator

fun main(args: Array<String>) {

    val numbers = intArrayOf(1, 4, 42, -3)

    if (4 in numbers) {
        println("numbers array contains 4.")
    }
}

When you run the program, the output will be:

numbers array contains 4.

Index access Operator

Here are some expressions using index access operator with corresponding functions in Kotlin.

Expression   	           Translated to
a[i] 	                   a.get(i)
a[i, n] 	           a.get(i, n)
a[i1, i2, .. , in] 	   a.get(i1, i2, .. , in)
a[i] = b 	           a.set(i, b)
a[i, n] = b 	           a.set(i, n, b)
a[i1, i2, .. , in] = b 	   a.set(i1, i2, .. , in, b)
    

Example: Index access Operator

fun main(args: Array<String>) {

    val a  = intArrayOf(1, 2, 3, 4, - 1)println(a[1])   
    a[1]= 12println(a[1])
}

When you run the program, the output will be:

2

12

Invoke Operator

Here are some expressions using invoke operator with corresponding functions in Kotlin.

Expression           	Translated to
a() 	                 a.invoke()
a(i) 	                 a.invoke(i)
a(i1, i2, in) 	         a.inkove(i1, i2, in)
a[i] = b 	         a.set(i, b)

In Kotlin, parenthesis are translated to call invoke method.

COMMENTS

Similar like Java, there are two types of comments in Kotlin

-INLine comments

fun main(args :Array<Strings>){//This is in line comments
println("Hello")
}

-MUTIPLE comments

 /*
 *Comment 1
 *Comment 2
 **/
 

** Kotlin Basic Input/Output**

Koltin Output

You can use println() and print() functions to send output to the standard output (screen). Let's take an example:

fun main(args : Array<String>) {
    println("Kotlin is interesting.")
}

When you run the program, the output will be:

Kotlin is interesting.

Here, println() outputs the string (inside quotes).

Difference Between println() and print()

print() - prints string inside the quotes.

println() - prints string inside the quotes similar like print() function. Then the cursor moves to the beginning of the next line.

Kotlin Input

To read a line of string in Kotlin, you can use readline() function.

Example 3: Print String Entered By the User

fun main(args: Array<String>) {
    print("Enter text: ")

    val stringInput = readLine()!!
    println("You entered: $stringInput")
}

When you run the program, the output will be:

Enter text: Hmm, interesting!
You entered: Hmm, interesting!

Functions

In programming, function is a group of related statements that perform a specific task.

Functions are used to break a large program into smaller and modular chunks.

Example:

fun main(args :Array<Strings>){
   
 var  name:String  
  name ="rohan"
  display(name) 
}

In kotlin to pass a value to function ,Simply define a variable with its data type.In runtime when display staement execute the value of variable name i.e rohan will follow down to function display() and print the value.

fun display(name:String){
 
 print(name)
}
    

To access th function of class we need to create object of the class.In case of java we create object of class using new keyword but in kotlin there is no such new keyword.So to access the object simple assign the class to variable as given below.

Example:

fun main(args :Array<Strings>){

   var name:String
   name="Rohan"var  studentObject=Student()
  studentObject.display(name);  
   
}
class Student(){
fun display(name:String){
  print(name)
 }
 }

Kotlin String

In java if you can to print the string with value we simple use the concatenation in print method.But in kotlin we had concept of string interpolation concept .Where we simple use $ sign followed by curly braces{} to declare the value within the double cots.

Example:

fun main(args :Array<Strings>){

   var name:String
   name="Rohan"var  studentObject=Student()
  studentObject.display(name);  
   
}

class Student(){
fun display(name:String){
 
 print("name"+name)
 //in kotlin you can access the name value within the "".
 print("name is ${name}")
 
 
 //by using the $ sign you can simply access the name
 }

Kotlin Class and Objects

Kotlin Class

Before you create objects in Kotlin, you need to define a class.

A class is a blueprint for the object.

How to define a class in Kotlin?

To define a class in Kotlin, class keyword is used:

class ClassName {
    // property// member function
    ... .. ...
}

Kotlin Objects

When class is defined, only the specification for the object is defined; no memory or storage is allocated.

Primary Constructors and named arguments

Another awesome feature I wish Java had, is the way you can more precisely call methods and constructors with named arguments.

Java:

Java, defining a class, typically looks like this:

public class User {

    private String firstName;
    private String lastName;
    private String email;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }

}
    

Kotlin:

Kotlin allows you to firstly get rid of the getters and setters, but also allows you to set variables in your class directly from the constructor

class User(
        var firstName: String = "",
        var lastName: String = "",
        var email: String = "") {

    override fun toString(): String {
        return "FirstName=${firstName}, LastName=${lastName}, Email=${email}"
    }

}

Interfaces

Interfaces in Kotlin are very similar to Java 8. They can contain declarations of abstract methods, as well as method implementations. What makes them different from abstract classes is that interfaces cannot store state. They can have properties but these need to be abstract or to provide accessor implementations.

An interface is defined using the keyword interface

interface MyInterface {
    fun bar()
    fun foo() {
      // optional body
    }
}

Implementing Interfaces

A class or object can implement one or more interfaces

class Child : MyInterface {
    override fun bar() {
        // body
    }
}

Static Functionality

Kotlin support static by Companion object.

An object declaration inside a class can be marked with the companion keyword:

class MyClass {
   companion object Factory {
       fun create(): MyClass = MyClass()
   }
}

Members of the companion object can be called by using simply the class name as the qualifier:

val instance = MyClass.create()

Final

In kotlin class are by default final,this means we cannot drive another class . To fix it we used open keyboard before class.

Conclusion

In this tutorial, you have learned how to use Kotlin in your Android projects after installing the Kotlin plugin and the Kotlin Android Extensions plugin for Android Studio. As Kotlin and Java classes are largely interoperable, if you are still learning Kotlin, it is best to introduce it in your Android projects gradually.To learn more about Kotlin, I recommend browsing the Kotlin reference.

Happy Coding!

I hope this article provided useful information about Kotlin.

Thank YOu!!!!

Preeti Dodani

Android Developer

5 年

Sahi Hann Boss

回复

要查看或添加评论,请登录

社区洞察

其他会员也浏览了