August 2017
Intermediate to advanced
440 pages
10h
English
The also function is similar to apply, with the only difference being that the parameter function accepts an argument as an parameter rather than as an receiver. It is preferable when we want to do some operations on an object that are not initializations:
abstract class Provider<T> {
var original: T? = null
var override: T? = null
abstract fun create(): T
fun get(): T = override ?: original ?: create().also { original = it }
}
The also function is also preferable when we need to do an operation in the middle of processing, for example, during object construction using the Builder pattern:
fun makeHttpClient(vararg interceptors: Interceptor) = OkHttpClient.Builder() .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(60, ...
Read now
Unlock full access