Basics
Kotlin Syntax
Kotlin Syntax Basics
Kotlin syntax uses semicolons optionally with null safety.
Introduction to Kotlin Syntax
Kotlin is a modern programming language that simplifies coding with its concise syntax. In this post, we will explore the basic syntax of Kotlin, focusing on the optional use of semicolons and the language's approach to null safety.
Optional Semicolons
Unlike many other programming languages, Kotlin does not require semicolons at the end of statements. However, you can use them if you prefer or if you need to put multiple statements on a single line.
In the code above, semicolons are not used. However, both of the following lines are valid in Kotlin:
Null Safety in Kotlin
Kotlin's type system is designed to eliminate null pointer exceptions, a common source of bugs. By default, variables cannot hold null values. If you wish to allow a variable to be null, you need to explicitly declare it as nullable by using a question mark (?
) after the type.
In the example above, name
is a non-nullable variable and cannot be set to null
. Conversely, nullableName
is a nullable variable and can hold a null
value.
Safe Calls and the Elvis Operator
Kotlin provides various operators to handle null values safely. One such operator is the safe call operator (?.
), which allows you to access a property or call a function on an object if it is not null. If the object is null, it returns null instead of throwing a NullPointerException.
The Elvis operator (?:
) is another feature that provides a default value if an expression on the left is null. It can be used to provide a fallback in case a nullable variable is null.
In this example, if nullableName
is null, lengthOrZero
will be assigned the value of 0.
Basics
- Previous
- Running Code
- Next
- Variables