Langsung ke konten utama

Kotlin - Basics


Hello Guys, we already knew that Google announced Kotlin is a new first class language for Android Development. So, we started the Kotlin series for learning Kotlin for android. We have seen the "Hello World" Program for Android in our previous post. 

You can download Intellij idea Commuinty Edition or use Kotlin Online Compiler provided by Intellij

In this post, we will learn the basics of kotlin.

1. Hello World

The Following Snippet shows the Hello world Program and is similar to Java.
fun main(args: Array <string>) {
println("Hello, world!")
}

2. Variables and Constants

The Following Snippet shows the How to use Variables and Constants with Datatype in Kotlin.
  1. Variables can be re-assigned 
  2. // Variable - Values Can be reassigned
    var a = 10
    a = a + 10
    println(a)
  3. Constants cannot be re-assigned and if we did will error as "val cannot be reassigned"
  4. // Constants - Values cannot reassigned
    val x = 10
    println(x)
  5. We can specify the Data types for Variables and Constants
  6. // Concate String Values
    println(str+"Mad")
    println("${str}Mad - Kotlin Series")
The following snippet shows how to use variables and constants.
fun main(args: Array<string>) {
// Variable - Values Can be reassigned
var a = 10
a = a + 10
println(a)
// Constants - Values cannot reassigned
val x = 10
println(x)
// Variables - with Datatype
var str : String = "Android"
println(str)
// Concate String Values
println(str+"Mad")
println("${str}Mad - Kotlin Series")
}

3. If Else

The Following Snippet shows the If Else Statement in Kotlin.
fun main(args: Array<string>) {
var arun = 10
var dharun = 15
var elder = if(arun > dharun)"Arun" else "Dharun"

println("Elder is ${elder}")
}

4. When

Switch statement is not present in Kotlin and is replaced by When.
fun main(args: Array<string>) {
var elder = "Dharun"
when(elder){
"Arun"->{
println("Elder is Arun")
}
"Dharun"->{
println("Elder is Dharun")
}
else->{
println("No Answer")
}
}
}

5. Loops

The Following snippet shows Loops in Kotlin.
// For Loop
fun main(args: Array<string>) {
for(i in 1..10){
println(i)
}
}
// While Loop
fun main(args: Array<string>) {
var x = 1;
while(x<=10){
println(x)
x++
}
}

6. Arrays and Lists

The Following snippet shows Arrays in Kotlin.
fun main(args: Array<String>) {
var x = arrayOf(1,2,3,4);
for(i in x){
println(i)
}
}
We can apply any type in like float, string ...
fun main(args: Array) {
var x = arrayOf(1,2,3,4,"Androidmads");
for(i in x){
println(i)
}
}
It Can be controlled by apply Data types as in the following Snippet
fun main(args: Array<String>) {
var x = arrayOf<String>("Android","Mads","Kotlin","Series");
for(i in x){
println(i)
}
}
Lists are similar to arrays
fun main(args: Array<String>) {
var x = listOf<String>("Android","Mads","Kotlin","Series");
for(i in x){
println(i)
}
}

7. Classes

The Following snippet shows how to declare / create objects for class in Kotlin. Create a class named it as "Model.kt"
class Model {
var name : String = ""
}
fun main(args: Array<String>) {
// In Java Object Created by ClassObject obj = new ClassObject();
var model = Model()
model.name = "Androidmads"
}

8. Constructors

The Following snippet shows how to use constructor in Kotlin.
class Model(val name:String, val age:Int)
We can also the following method
class Model{
constructor(name:String, age:Int) {

}
}
fun main(args: Array<String>) {
// In Java Object Created by ClassObject obj = new ClassObject();
var model = Model("Androidmads",20)
println("${model.name}")
}

9. Null Handling

In Java, Null value may leads to Null Pointer Exception. But, In Kotlin,Null Handling to variables is done as in the following snippet
fun main(args: Array<String>) {
var name:String? = null
// Just prints Null and does not throw NullPointerException
println("${name}")
}
Hope you Like this. Post Comments about this article in Comment Section 

Komentar

Postingan populer dari blog ini

Android Tutorial: Use LeakCanary to detect memory leaks

Overview The memory leak can be a headache to detect and to resolve, small memory leaks can be hidden and may be seen after a long usage of the application and hunting memory leaks is not a simple task. In this tutorial we will create a leaked application and we will use the LeakCanary library to detect the memory leak. Step 1: add the LeakCanary dependency to the application Modify the app/build.gradle to add the LeakCanary dependency as follows: Step 2: Extend and configure the Application class We need to call LeakCanary.install in onCreate method: Step 3: Create a leaked activity For this we will create a singleton class that saves the context: Then, the main activity (leaked one), will use the singleton and then we'll go to a new activity: Then, in the new activity we'll call System.gc to force the garbage collector in order to accelerate the analysis. Step 4: Retrieve the analysis result A nice notification can be shown: The result can be retrieved from logcat: Source c...

QR-Code Generator - Library

In this Post, I introduce my new Gradle Library. This Library is used to Generate QR Code Automatically for our specified input. How to Import the Library: Gradle: compile 'androidmads.library.qrgenearator:QRGenearator:1.0.0' Permission: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> How to use this Library: After importing this library, use the following lines to use this library. The following lines are used to generated the QR Code // Initializing the QR Encoder with your value to be encoded, type you required and Dimension QRGEncoder qrgEncoder = new QRGEncoder(inputValue, null, QRGContents.Type.TEXT, smallerDimension); try { // Getting QR-Code as Bitmap bitmap = qrgEncoder.encodeAsBitmap(); // Setting Bitmap to ImageView qrImage.setImageBitmap(bitmap); } catch (WriterException e) { Log.v(TAG, e.toString()); } Save QR Code as Image // Save with location, value, bitmap returned and type of Image(JPG/PNG). QRGSaver.save(s...

FlatBuffers Android Tutorial

FlatBuffers is an efficient cross platform serialization library for C++, Java, C#, Go, Python and JavaScript. It was originally created at Google for game development and other performance-critical applications. FlatBuffers is Open Source (Apache license V2) and available on GitHub . It's currently used by:   Cocos2d-x , the open source mobile game engine and used to serialize the game data. Facebook uses it for client-server communication in the Android app (see the article) . Fun Propulsion Labs at Google in most of libraries and games. Solution overview  The schema will be defind in JSON format, then it will be converted to FlatBuffer format outside the application The Java classes of the Data model will be generated manually using flatc (FlatBuffer compiler) Step 1: Build FlatBuffers Download the source code in Google’s flatbuffers repository .  The build process is described on Google's documentation FlatBuffers Building .  On MacOS for example: Open the ...