Learn Kotlin gist for android developers part- 2

Anko and Extension Functions — 7

What is Anko?

Its main purpose is the generation of UI layouts by using code instead of XML. Anko includes a lot of extremely helpful functions and properties that will avoid lots of boilerplate.

Extension functions

An extension function is a function that adds a new behaviour to a class, even if we don’t have access to the source code of that class.

fun Context.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) {
Toast.makeText(this, message, duration).show()
}
toast("Hello world!")
toast("Hello world!", Toast.LENGTH_LONG)

Retrieving data from API — 8

Performing a request

General way:

class Request(val url: String) {
fun run() {
val forecastJsonStr = URL(url).readText()
Log.d(javaClass.simpleName, forecastJsonStr)
}
}

Performing the request out of the main thread

Anko provides a very easy DSL to deal with asynchrony. It basically provides an async function that will execute its code in another thread, with the option to return to the main thread by calling uiThread

async() {
Request(url).run()
uiThread { longToast("Request performed") }
}
val executor = Executors.newScheduledThreadPool(4)
async(executor) {
// Some task
}

Data Classes — 9

Copying a data class

if we want to change the state of an object, a new instance of the class is required, with one or more of its properties modified. However, data classes include the copy() method.

val f1 = Forecast(Date(), 27.5f, "Shiny day")
val f2 = f1.copy(temperature = 30f)

Mapping an object into variables

This process is known as multi-declaration and consists of mapping each property inside an object into a variable.

val f1 = Forecast(Date(), 27.5f, "Shiny day")
val (date, temperature, details) = f1
for ((key, value) in map) {
Log.d("map", "key:$key, value:$value")
}

Parsing data — 10

Converting json to data classes

A good practice explained in most software architectures is to use different models for the different layers in our app to decouple them from each other.

Shaping the domain layer

First, a definition of a Command is required:

public interface Command<T> {
fun execute(): T
}
return list.map { convertForecastItemToDomain(it) }

Drawing the data in the UI

Operator overloading — 11

Operators tables

Here you can see a set of tables that include an operator and its corresponding function.

Unary operations

+a    a.unaryPlus()
-a a.unaryMinus()
!a a.not()
a++ a.inc()
a– a.dec()

Binary operations

a+b       a.plus(b)
a-b a.minus(b)
a*b a.times(b)
a/b a.div(b)
a%b a.mod(b)
a..b a.rangeTo(b)
a in b b.contains(a)
a !in b !b.contains(a)
a += b a.plusAssign(b)
a -= b a.minusAssign(b)
a *= b a.timesAssign(b)
a /= b a.divAssign(b)
a %= b a.modAssign(b)

Array-like operations

a[i]     a.get(i)
a[i, j] a.get(i, j)
a[i_1, …, i_n] a.get(i_1, …, i_n)
a[i] = b a.set(i, b)
a[i, j] = b a.set(i, j, b)
a[i_1, …, i_n] = b a.set(i_1, …, i_n, b)

Equals operation

a == b    a?.equals(b) ?: b === null
a != b !(a?.equals(b) ?: b === null)

Operators in extension functions

We could access to ViewGroup views the same way we do with lists:

operator fun ViewGroup.get(position: Int): View
= getChildAt(position)
val container: ViewGroup = find(R.id.container)
val view = container[2]

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Md Ali Hossain

Md Ali Hossain

Senior Android Engineer @Delivery Hero | Android developer | Kotlin lover | Flutter explorer | Problem Solver