Basic Grammer for Kotlin


This article introduces you to the basic Kotlin grammar.

๐Ÿ˜ธ !!

!! converts T? to T. If the coverted object is null, app will throw a exeption.

val list: List<Int> = ...
val maxValue = list.max()!!
val square = maxValue * maxValue

๐Ÿ˜Ž ?.let

?.let ใฏ null ใ˜ใ‚ƒใชใ„ๅ ดๅˆใซๅ‡ฆ็†ใ‚’่กŒใ†ใƒกใ‚ฝใƒƒใƒ‰ใ€‚

?.let is a function to process if an object is not null.

map[1]?.let { it + 5 }

๐Ÿ€ init in Class

Pre-checking with init in an object disallows a malformed state:

class Age(private val ageInt: Int) {
init {
require(isValid()) { "Support $MIN_AGE <= age <="$MAX_AGE" }
}

companion object {
private const val MIN_AGE = 0
private const val MAX_AGE = 120
}

fun value(): Int {
return ageInt
}

private fun isValid(): Boolean {
return ageInt in MIN_AGE..MAX_AGE
}
}

๐Ÿค” References

๐Ÿ–ฅ Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!