In principle, I agree with the comments that this topic is superfluous, since there are automatic code formatting tools
And besides, everyone has their own opinion about beauty and aesthetics, so the coding style is subjective.
But I decided to finish this series of articles on Kotlin style, as promised.
Perhaps someone will come in handy.
Well, please, under the cut!
Naming
Identifiers of variables, functions, properties, classes use only ASCII letters and numbers (ordinary English letters + 10 digits)
(: _digit, power_
) (: Backing ).
.
: (: fetchDogs
) (makeRepost
)
, , :
@Test fun get_emptyList() {
// ...
}
, @Composable
(Jetpack Compose ) , , Pascal :
@Composable
fun MyDog(name: String) {
// …
}
, .
Kotlin - val
, get
, . :
(listOf(1, 2, 3)
), , const:
// const
const val FIVE = 5
val MY_DOGS = listOf("Dina", "Red")
val EMPTY_ARRAY = arrayOf()
object
( ).
, , .
, , . .
val viewModel by viewModels<DogViewModel> { viewModelFactory }
val firstName = "Anna"
val dogs = listOf(Dog("Dina"), Dog("Red"))
lateinit var binding: ListItemBinding
fun fetchDogs(page: Int): List<Dog> {
// ...
}
backing :
private val _dogs = MutableLiveData<List<Dog>>()
val dogs: LiveData<List<Dog>>
get() = _dogs
generic :
( , :
T1, T2, R1
)
generic , T (:
RequestT, ResponseT
)
, generic .
Pascal (: SleepingDog
- ).
(: MyCar
- )
. (: Cloneable, Readable, Writable
):
class MainActivity(): AppCompatActivity() {
// ...
}
interface OnItemListener {
fun onItemClick(id: Long)
}
interface Readable {}
: :
//
package com.example.android.marsRealeState.overview
//
package com.example.android.mars_reale_state.overview
// OK
package com.example.android.marsrealestate.overview
enum :
enum class NetworkStatus {
SUCCESS, FAILED, LOADING
}
: , :
enum class NetworkStatus {
SUCCESS,
FAILED,
LOADING {
override fun toString() = "loading..."
}
}
, .
, :
//
@Singleton
@Component(modules = [DatabaseModule::class])
interface AppComponent {
// ...
}
// ,
@JvmField @Volatile
var disposable: Disposable? = null
// :
@Inject lateinit var viewModelFactory: DogViewModelFactory
:
//
override fun toString(): String = "My name is $name"
//
override fun toString() = "My name is $name"
//
private val redDog: Dog = Dog("Red")
//
private val redDog = Dog("Red")
KDoc :
/**
*
*
*/
fun fetchDogs(page: Int) {
// …
}
:
/** */
:
, (
*
),
:
@constructor
,@receiver
,@param
,@property
,@return
,@throws,@see
KDoc , (: "This function returns sum of digits").
, KDoc , , , public API.
, , :
// , .
fun sum(a: Int, b: Int) = a + b
, , , .
: KDoc , .
.
, , : , , Android Studio, !
: " Android ?"
: