Let's now discuss some of Kotlin's syntactic rules and coding guidelines:
- Class name: As in Java, class names begin with an uppercase letter. We can create it with a lowercase letter, but it is recommended that we use an uppercase letter, as per the Java coding convention. This is to keep the convention the same when dealing with both Java and Kotlin files.
- Packages: Specify the package at the top of the class. Packages are written in lowercase letters separated by a dot(.):
package org.rao.kotlin.intro
Note that the semicolon is optional in package declarations in Kotlin.
- Imports: The imports should be after the declaration in the class file. If there is no package statement, the import statement should be the first statement. An example of an import statement is as follows:
import java.util.List
- Variables: In Kotlin, var and val are used to declare variables. Use camelCase when declaring variables and provide meaningful names for them. Some examples are shown in the following table:
Examples |
Explanation |
val number = 10 |
Here, the type Int is inferred. We can use this syntax in local contexts in code. |
val number: Int = 10 |
Here, the type Int is declared explicitly and a value is assigned. |
val number: Int |
Here, a variable is declared but not initialized. Declaring the type is required in this case. |
var userName = "Bob" |
Here, we used var to create a mutable variable, which is initialized. Because of this, the type is optional and is inferred from the context. In this case, the type inferred is String. |
- Comments: Kotlin has support for single-line and multiline comments:
// This is single line comment
/* This is a multi-line
comment. */
Unlike Java, Kotlin also supports nested comments:
/*
Top level comment section
/*
Nested comments section
*/
*/
- Operators: Use the in operator to check whether a number is in a specified range or in loops for iteration:
if(number in 1..5)
for(number in 1..5)
Similarly, use the is operator to check the type. When we use the is operator, explicit type casting is not required:
fun processInput(input: Any) {
if(object is String) {
var data: String = object
}
}
Note the automatic type conversion that is applied when using the is operator in this context. Outside this context, the type will be Any. This is a super type in Kotlin, like Object in Java.
Kotlin provides an easy and flexible syntax compared to Java. This helps us write concise and more expressive code that is easy to maintain.