Skip to main content

Kotlin Basic Syntax

In this section are mentioned about overview of kotlin basic syntaxes and coding styles. This post is useful for understanding basic concept of kotlin programing. Syntactically kotlin is very similar to java programming. But kotlin is support both functional and object oriented programming. Lets view first an example of this point.

fun main(args: Array<String>) {
    println("Hello World!") //display message
}

Output

Hello World!

Semicolons is not an compulsory.

print() and println() is used to display message of constant string and value of variables. and println() is display next upcoming message in new line.

Kotlin comments

kotlin comment is similar to java, c and c++ programming language. single line comment define by double forward slash (//). and multi line comment is defined by single forward slash and abstric and end with abstract and forward slash (/* comment section */).

fun main(args: Array<String>) {
   //This is an single line comment
    
   /*
     This is an multi line comment portion 
     Here possible to define more 
     Than one line text document
   */ 
}

kotlin variable

Variable is like a value holder container which are store the some information. We can declared variable of kotlin programming in two different way. There is available of 2 keywords to define is variable. first is var keyword. This are normally used to define variable which are not constant. That means this type of variable value are can be change at any place of exist the scope of this variable. There is declared of follows.

 var variableName:dataType = values

For example.

fun main(args: Array<String>) {
   //integer variable declared, and assign its value 
   val intData:Int =10
    //String variable declared, and assign its value 
   var textData:String ="Kotlin Programming" 
   println(intData)
   println(textData) 
}

Output

10
Kotlin Programming
Kotlin - variable declaration

Note that value of variable is an optional when declare of any normal variable. And var variable is mutable. See this example.


fun main(args: Array<String>) {
   //Declaration of variables    
   var age:Int //Declared Integer variable
   var name:String //Declared String variable
  
   //initialized variable values 
   age = 21
   name="Foo" 
   println(age)
   println(name)
    
   //modified variable values
   age = 10
   name="Bar" 
   println(age)
   println(name) 
}
     

Output

21
Foo
10
Bar

Before used of variable, should be assigning the value of those variables. Otherwise compiler produces error. See this examples.

fun main(args: Array<String>) {
   //Declaration of variables    
   var age:Int
   var name:String 
   //No set any value to variable and tried to use
   println(age)
   println(name) 
}

Error

source.kt:6:12: error: variable 'age' must be initialized
   println(age)
           ^
source.kt:7:12: error: variable 'name' must be initialized
   println(name) 

One of the common mistake can be possible. kotlin is strongly check data type before assign value to variable. If type is not match then compiler is produced an error.

fun main(args: Array<String>) {
   //Declaration of variables    
   var myData:Int //myData is an integer variable
   myData=100 //okay valid integers
   println(myData)
    
   myData=100.77 //error
   println(myData)
}

Error

source.kt:7:11: error: the floating-point literal does not conform to the expected type Int
   myData=100.77 //error
          ^
source.kt:8:4: error: overload resolution ambiguity: 
@InlineOnly public inline fun println(message: Any?): Unit defined in kotlin.io
@InlineOnly public inline fun println(message: Double): Unit defined in kotlin.io
@InlineOnly public inline fun println(message: Int): Unit defined in kotlin.io
   println(myData)
   ^

Immutable variable is to defined by val keyword in kotlin.

val variableName:daTaType = value

For example.

fun main(args: Array<String>) {
   //Declaration of constant variables    
   var pi:Float =3.141593f //variable value is Immutable
   print(pi)
}

Output

3.141593

This variable value will be assigned of only once. And after that cannot modified during program execution.

fun main(args: Array<String>) {

  val days:Int //Define constant variable

  days=10 //Okay Assign this value At first time

  days=15 //Error cannot modified

  print(days)
}

Error

kotlin.kt:7:2: error: val cannot be reassigned
  days=15 //Error cannot modified
 ^

val variable are in form of read only that can not modified.

Compile time constant: is a process to define constant variable in outside the function. in this situation when compiler this source code, compiler are assign constant variable value in compile time. and this value are never modified or updates in during program execution. For example.

//Example compile time constant
const val NATURE :String ="Green"
fun main(args: Array<String>) {
   //display value
   println(NATURE)
}

Output

Green

Note that val is an readonly variables. that cannot modified itself. But when define of val variable as function parameter, In this case that value are change when passing of its value to that function. So val variable is read only variable. And const keyword are used to define constant variable in kotlin programing. When constant variable is define outside of all function. In this situation value of this variable are set at compile time. And as naming convention define name of constant variable are capitalizing letter.

Scope of variable is related to defined region of accessibility and use. The scope of kotlin variable is dependent upon block level.

fun main(args: Array<String>) {
  
  var x:Int =10

  if(x>0){
    println("x : $x")
    var y:Int =x*x  //local variable y
    println("y : $y")
  }
  //y not access outside the block

}

Output

x :10 
y :100

In this example y variable is defined inside if condition. therefore that is not access outside of this block.

Type Inference

kotlin compiler are strongly check what is the type of variables and which type of value that can store. This is depends upon type of variable. Type inference of variable are used to clear indication of variable behaviors. Generally programmer are define variable first and assign there value in latter. And that are also useful for compiler when implement single line function. See this example.

//square function are return
//square of given int.
//return an integer value
fun square(x:Int)= x*x

fun main(args: Array<String>) {

  println(square(3));
   
}

Output

9




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment