/kotlin-lunch-learn

Project written on kotlin as part of lunch and learn presentation

Primary LanguageKotlinThe UnlicenseUnlicense

Kotlin lunch and learn

Project written on kotlin as part of lunch and learn presentation.

No more one file one class rule. Any amount of classes can be in one file. To declare a class put Class keyword and class name. By default all classes in Kotlin are public and final. To make a class not final use open modifier.

Similar to a class declaration but with interface keyword. Although functions can have default implementation just like in Java 8.

Two types of constructors exist in Kotlin - primary and secondary

Primary constructor

Primary constructor is a part of a class header. Every declared parameters became properties. To write any initialization code init block can be used. All parameters from the constructor available there. Primary constructor can be only one for a class. Although visibility modifier can be applied.

Secondary constructor

Can be declared more than one. If primary constructor defined for a class each secondary constructor needs to delegate to primary constructor

No more getters and setters like in Java. Property can be defined by using val and var keywords.

val read only property

var modifiable property

Functions can be declared without a class (package level functions). To define a function use fun keyword, function name and returning type. Returning type can be omitted if function returns nothing. One line functions can be simplified by using = and statement. Parameters can have default values. Also parameter's name can be used when calling function

Kotlin provides ability to extend a class with new functionality without having to inherit from the class or creating Util class. To declare extension function use receiver type as prefix and function name. This keyword corresponds to to the receiver object.

For classes which contains only data Kotlin has a concept of data class. To use that ability add data keyword before the class and declare primary constructor with some fields. Kotlin compiler generates for you - equals, hashCode and toString functions.

In Kotlin's type system by default all types can't be null. To be able to use nullable type put ? after the type. To be able to call functions from nullable type use safe call by using ? after variable name. If variable will be null result of function invocation will be also null. In case of checking variable for a null value no need to use safe call operator. Also function let can be used for that purpose. Elvis operator ?: can provide default value in case of null value. Operator !! can be used instead of safe calls in case of null value NullPointerException will be thrown.