Getting Started Guide basic syntax definition package
The declaration of the package must be at the top of the source file:
Package My.demo
Import java.util.*
Java different packages do not have to match the directory structure: the source files can be placed anywhere on the file system.
function definition
Here is an example of a parameter with two int types and an int return value:
Fun sum (A:int, b:int): Int {
Return a + b
}
Using an expression as a function body compiler can automatically infer the return type:
Fun sum (a:int, b:int) = a + b
function with no return value:
Fun Printsum (A:int, B:int): Unit {
Print (A + B)
}
The unit return type can then be omitted:
Fun Printsum (A:int, B:int) {
Print (A + B)
}
Local variable definition
Disposable Assignment (read-only) Local variables:
Val A:int = 1
Val B = 1//int type inference
Val c:int//variable with no initialization must specify type
c = 1//Explicit specified value
Variable variable:
var x = 5//' Int ' type is inferred
x + = 1
Comments
Just like Java and JavaScript, Kotlin supports line comments and block annotations.
Here is an explanation of the line
/* This was a block comment on multiple lines. */
Unlike Java, Kotlin block annotations support nesting.
String templates
Fun Main (args:array<string>) {
if (args.size = = 0) return
Print ("First argument: ${args[0]}")
}
Conditional expressions
Fun Max (A:int, b:int): Int {
if (a > B)
Return a Else
Return b
}
Use if as expression: Fun Max (A:int, b:int) = if (a > B) a else B
Nullable and Null value checks
Reference types that may be null values must be explicitly identified as nullable
Returns null if STR is not a valid number string
Fun parseint (str:string): Int? {
// ...
}
A function that returns a nullable type value:
Fun Main (args:array<string>) {
if (Args.size < 2) {
Print ("Integers expected")
Return
}
Val x = parseint (Args[0])
Val y = parseint (args[1])
Using ' x * y ' directly will make an error, as they may contain null values
if (x! = null && y! = null) {
X and Y are automatically converted to non-nullable types after a null check operation
Print (x * y)
}
}
Or
if (x = = null) {
Print ("Wrong number format in ' ${args[0]} ')
Return
}
if (y = = null) {
Print ("Wrong number format in ' ${args[1]} ')
Return
}
X and Y is automatically cast to non-nullable after null check
Print (x * y)
Type checking and automatic type conversion
The IS operator is used to check whether an expression is an instance of a specified type. If an immutable local variable or property is checked for the target type, then no explicit type conversions are required:
Kotlin programming language