Kotlin wurde erst vor 5 Jahren erstellt und gilt seit 2019 als vorrangige Programmiersprache fĂŒr Android. Und doch ist diese Sprache noch recht jung und entwickelt sich weiter. Manchmal ist nicht klar, wie man den Code am besten schreibt. In unserem Team fĂŒhren wir hĂ€ufig Diskussionen zum Thema reinen Kotlin-Code, und auf deren Grundlage haben wir unsere Best Practices zusammengestellt. Wir möchten diese Empfehlungen teilen und freuen uns auf Ihre Fragen.
Nun, fangen wir an! Erstens gibt es in Kotlin viel syntaktischen Zucker, und wenn er ĂŒberbeansprucht wird, wird es schwierig, solchen Code zu lesen. Die nĂ€chsten Punkte sind auf den Kampf zwischen KĂŒrze und Lesbarkeit zurĂŒckzufĂŒhren .
Schreiben Sie keine Klassendeklaration in eine Zeile
â . .
class ChannelViewModel(
val conversationId: String,
getChannelUseCase: GetChannelUseCase,
) : ViewModel() {
, :
, ( Android Studio / Shift+Command+Up/Down)
.
return
:
data class MyClass(val number: Int, val flag: Boolean)
fun create(numberParam: Int?, flag: Boolean?): MyClass? {
return MyClass(numberParam ?: return null, flag == true)
}
return, , . , numberParam null, return MyClass(...) return null. if, :
fun create(numberParam: Int?, flag: Boolean?): MyClass? {
if (numberParam == null) {
return null
}
return MyClass(numberParam, flag == true)
}
it
values?.filterNot { selectedValues?.contains(it) == true }
?.let {
selectedValues?.addAll(it)
result[key]?.values = selectedValues?.filter { it.isChecked }
}
let:
values?.filterNot { allSelectedValues?.contains(it) == true }
?.let { newValues ->
allSelectedValues?.addAll(newValues)
result[key]?.values = allSelectedValues?.filter { it.isChecked }
}
it â . -null, . :
val newValues = values.filterNot { selectedValues.contains(it) }
selectedValues.addAll(newValues)
result[key]?.values = selectedValues.filter { it.isChecked }
?. -null
:
private var animatedView: FrameLayout? = null
...
animatedView?.animate()?.alpha(1f)?.setDuration(500)?.interpolator = AccelerateInterpolator()
null , animatedView null. if (animatedView != null) . , animatedView null. lateinit , null:
private lateinit var animatedView: FrameLayout
...
animatedView.animate().alpha(1f).setDuration(500).interpolator = AccelerateInterpolator()
Java Kotlin, â â. . Java - if when, (let, apply, also, with, run), , Utils extension .
!!
!! , NullPointerException, !! ââ.
!! :
-null ( lateinit animatedView)
let ?.let { ⊠}
- ?:
, , , null, checkNotNull requireNotNull. : IllegalStateException IllegalArgumentException .
, !! Java Kotlin, @NonNull Java-.
when if
:
val price = if (priceData.isWeightPrice) {
priceData.minDiscountPrice.toInt()
} else if (priceData.discountPrice != 0.0) {
priceData.discountPrice.toInt()
} else {
priceData.price.toInt()
}
when:
val price = when {
priceData.isWeightPrice -> priceData.minDiscountPrice.toInt()
priceData.discountPrice != 0.0 -> priceData.discountPrice.toInt()
else -> priceData.price.toInt()
}
when , , .
when , . , when .
Util
- , extension. .
, . , , .
, Util Kotlin ( : Java , Kotlin â ). - , (package) . (extension , , ; , - ). , , , .
, ( â â). , .
(trailing commas)
1.4. ( ) : diff .
Single Abstract Method interface (Fun interface)
Kotlin 1.4.0. , fun :
this.actionClickListener = object : BubbleView.ClickListener {
override fun onBubbleViewClick() {
...
}
}
this.actionClickListener = BubbleView.ClickListener {
...
}
fun:
fun interface ClickListener {
fun onBubbleViewClick()
}
, Java, Kotlin , SAM- . :
(T) -> R;
, SAM-;
, .
?
val itemIdsSet: Set<String> = ...
val currentItemIds: Set<String> = ...
for(itemId in itemIdsSet) {
if(!currentItemIds.contains(itemId)) {
repository.exclude(itemId)
}
}
:
val itemIdsSet: Set<String> = ...
val currentItemIds: Set<String> = ...
for (itemId in itemIdsSet subtract currentItemIds) {
repository.exclude(itemId)
}
API , exclude , :
repository.exclude(itemIdsSet subtract currentItemIds)
code style
, ââ. :
(, _ enum )
companion object ( ) ..
, . , best practices.
, Kotlin- :
https://developer.android.com/kotlin/style-guide https://proandroiddev.com/an-opinionated-guide-on-how-to-make-your-kotlin-code-fun-to-read-and-joy-to-work-with-caa3a4036f9e
https://developer.android.com/kotlin/coroutines/coroutines-best-practices