From Java to Kotlin - Kotlin vs Java & Tools

Java features that Kotlin lacks

  • Checked exceptions
  • Primitive types that aren’t classes
  • Static members
  • Non-private fields
  • Wildcard types

Functional Programming in Kotlin

What is Functional Programming

Creating software by writing functions, avoiding shared state, using immutable data and causing no side-effects.

It’s declarative rather than imperative. Application state flows through pure functions.

Declarative program logic is expressed without explicitly describing the flow control.
Functional Programming uses lots of generics and reusable code (lambdas).

Functional Programming Terminology

  • Pure functions
    • you work with functions as values. You can store them in variables, pass them as parameters or return them from other functions
    • given the same inputs, always returns the same output. Tshey have no side-effects.
  • Function Composition
    • process of combining two or more functions in order to produce a new function or perform some computation
  • Shared State
    • any variable, object or memory space that exists in a shared scope or as the property of an object passed between scopes instead of relying on immutable data structures.

Immutability and Side Effects

Immutability An object can’t be modified or change its state after its creation. Immutability is a central concept of functional programming because without it, the data flow in your program is changing. Through immutability we avoid side effects.

Advantages

Code tends to be more concise, more predictable and easier to test than imperative or object oriented code.
Gives the programmer the ability to provide abstraction better, which lets you avoid duplication in your code.
Immutability allows for safe multithreading.

Kotlin Support for Functional Programming

Functional types allowing functions to receive other functions as parameters or return other functions
Lambda expressions letting you pass around blocks of code with minimum boilerplate
A rich set of APIs in the std library for working with objects and collections in the functional approach
Kotlin supports FP but you’re not required to use it.

Kotlin Tools

Java-to-kotlin converter

It’s a menu option inside the IDE Code > Convert Java File to Kotlin File
You can write Java and it converts it into Kotlin. It’s a great way to learn Kotlin and improve or when you don’t remember the exact syntax.

There’re also online converters.

Kotlin Android Extensions and Anko

Allows developers to perform basic android functions using libraries without having to add any extra code and allow you to get rid of findViewById() calls in your code.

Anko is a library providing a set of Kotlin-friendly wrappers around the Android APIs as well as a DSL (Domain Specific Languages) that lets you replace your layout .xml files with Kotlin Code.