Kotlin Basics I
Heya fellow coders! Please come closer and join my journey with Kotlin:
I developed apps with swift. When i have used kotlin for the first time, i knew it looks so similar to swift. This ease my process of getting used to it.
Declarations
I prefer explaining things on code for this part;
Key points:
It has nullable variables and swift way of declaring variables
You don’t need to define type if you give a value to variable (a.k.a dynamic typing)
Arrays, List and Map Declarations:
There are two types of collections; mutable and immutable. List and map are immutable. After you declare them, you cannot change their elements. If you want to change contents without creating mutable collection, there is a tricky way. If you pass another mutable list as declaration; when you change referred mutable list, you also change contents of immutable list. Don’t use this trick but it is shown on this example;
Remember that intArray and array does not have any relation. Thus, intArray and intArr variables are two different types.
When a property is defined, it will have default get and set functions. Read-only properties(val) does not allow setter. If you want to define different getter and setter, you can do it like this;
field is special keyword for accessing current variable. It is called as backing field. If you want to be familiarize with them, think it as this keyword which is used in instances to access current instance
Inside of defining with final static, you can define constant variables with const keyword(a.k.a compile time constant);
const val MSG_INVALID_DATA = “Please enter a valid number”
However it have three rules; only use primitive types or string, cannot have custom getters and have to be at the top of class.
Strings:
You can access variables inside of String by fancy ${variableName} operator. There are two different way to define string literals; escaped one and raw one;
Control Operators
I love range operator in swift. It feels like upgraded version for traversing in an array. Luckily kotlin has same ability too!
Destructing operator is also called componentN() functions. You can use this to break down a class or map to multiple variables in one declaration.
Comparison Operator
Kotlin provides a new way to use ternary operator by “if-else” case;
fun compare(a: Int, b: Int) {
// used as value expression
val max = if (a > b) a else b
print(“ Max value is ${ max }”)
}
PS: Ternary operator is (condition) ? true-case : false-case)
Switch operator is changed completely!
Keep in mind that, else condition is mandatory if “when” is used as expression. You use negated version of “in” operator. Same rule applies for type check operator “is” and it will be explained soon!!
Other control operators remained same.
Equality
There are two ways to compare equality of properties; referential and structural(equals()). Referential equality check if objects refers to same point in memory.
Type Checks
instanceof operator is changed. Compiler does smart cast operator for you when it sees the use of “is” operator. After evaluation of control, you can use variables directly without casting. For example, obj in this example;
// for non-null objects
// negated version !is
if (obj is Vehicle) {
obj.startCar()
}
// for nullable objects
if (obj is Vehicle?) {
var vehicle = obj // If object is null, then vehicle is null
}
There is a negated version of is: !is.
There is cast operator. It is called “as” . It is unsafe because it throws an exception if cast is not possible.
var num = 3
var value = num as String
// causes -> java.lang.ClassCastException: java.lang.Integer cannot // be cast to java.lang.Stringvar value = num as? String
// this is safe version, assigned value is null because
// cast is not possible
Functions
Functions have default parameters and named parameters which java does not have. If you know Swift, you will see similarity on function definitions;
Last example uses destructing operator on return. They are similar to Tuples. You can use this to return multiple results from a function without creating custom object.
Exceptions
All exception are descendants of Throwable class.
Fun facts about throw:
Type is throw is Nothing. It is not a joke and yes this type exists. Nothing points unreachable place. When you call a function that returns “Nothing”, code segments that comes after that function will never be implemented.
fun error(): Nothing {
return throw IOException(“”)
}
error()
print(“enter”)
// never prints enter
Also, if a variable initialised with null and does not have any type, it will inferred as “Nothing?” by compiler.
Thanks for reading my first article on Kotlin, and clap if you liked it!!