Kush Patel
03/06/2021, 1:13 AMapply {}
does in order to understand the code. I am more curious to understand if there is some sort of tradeoff I’m missing here if one chooses A over B or vice versa. Thanks!
// A
val setOfInts = HashSet<Int>().apply{
for (i in 0..20) {
this += i
}
}
// B
val setOfInts = mutableSetOf<Int>()
for (i in 0..20) {
setOfInts.add(i)
}
Zach Klippenstein (he/him) [MOD]
03/06/2021, 1:18 AMsetOfInts
was being defined as a property on a class, where the more imperative B wouldn’t be possible without adding an init{}
blockZach Klippenstein (he/him) [MOD]
03/06/2021, 1:19 AM+=
operator in B as wellKush Patel
03/06/2021, 1:47 AMsetOfInts
is not a property on a class so would I really benefit from using apply?
I can't think of a reason why I should use apply
over += in Bedrd
03/06/2021, 1:48 AMval setOfInts = HashSet<Int>().also { set ->
for (i in 0..20) {
set += i
}
}
edrd
03/06/2021, 1:53 AMval setOfInts = (0..20).mapTo(HashSet()) { it }
Kush Patel
03/06/2021, 1:57 AMShawn
03/06/2021, 2:48 AM(0..20).toHashSet()
Kush Patel
03/06/2021, 4:39 AMapply {}
to populate a collection rather than doing it in an imperative way like Bedrd
03/06/2021, 2:11 PMapply
is useful to avoid repeating the receiver. For example:
fun buildDataSource(dbConfig: DbConfig): DataSource {
val dataSource = HikariDataSource()
dataSource.jdbcUrl = dbConfig.url
dataSource.username = dbConfig.user
dataSource.password = dbConfig.password
dataSource.idleTimeout = Duration.ofMinutes(2).toMillis()
dataSource.maxLifetime = Duration.ofMinutes(10).toMillis()
return dataSource
}
versus with `apply`:
fun buildDataSource(dbConfig: DbConfig): DataSource {
return HikariDataSource().apply {
jdbcUrl = dbConfig.url
username = dbConfig.user
password = dbConfig.password
idleTimeout = Duration.ofMinutes(2).toMillis()
maxLifetime = Duration.ofMinutes(10).toMillis()
}
}
Tyler Hodgkins
03/08/2021, 8:38 PMA
to initialize a set mutably but not expose the mutable set to the outer scope.
val setOfInts = mutableSetOf<Int>().apply {
for(i in 0..20) {
this += i
}
}.toSet()
The type of setOfInts
in this case is Set
rather than MutableSet
. Using apply
allowed this to all be done in a single line of code.Tyler Hodgkins
03/08/2021, 8:40 PM