안녕하세요 공공돌🧸 입니다 !!
오늘은 코틀린 코드 컨벤션에서 서식 지정(Formatting)에 대해 설명해보려고 합니다.
서식 지정의 경우 들여 쓰기, 가로 공백, 콜론, 클래스 헤더, 수정자 순서, 등 15개로 구성이 되어있어 3개씩 올리도록 하겠습니다 !
다른 서식 지정에 관한 글은 맨 아래 링크에 정리가 되어 있으니 들어가서 한 번씩 봐주세요 😳😳
자세한 코틀린 코드 컨벤션은 아래 링크에서 보실 수 있습니다.
서식 지정(Formatting)
들여 쓰기( Indentation )
들여쓰기에는 Tab을 사용하지 않고 공백 4개를 사용합니다.
중괄호의 경우 여는 중괄호를 구문이 시작되는 줄 끝에 배치하고 닫는 중괄호를 여는 구문과 수평으로 정렬된 별도의 줄에 배치합니다.
if (elements != null) {
for (element in elements) {
// ...
}
}
가로 공백( Horizontal whitespace)
1. 이진 연산자( a + b) 주위에 공백을 넣습니다. (예외: "범위" 연산자(0..i) 주위에 공백을 두지 마십시오.
연산자 사이에 공백을 추가하여 코드를 더 읽기 쉽게 만듭니다.
하지만 범위 연산자(0..i) 주위에는 공백을 넣지 않습니다.
// 올바른 사용
val result = a + b
// 예외 범위 연산자
for (i in 0..i) {
// ...
}
2. 단항 연산자( a++ ) 주위에 공백을 넣지 마십시오.
단항 연산자 주변에는 공백을 추가하지 않습니다.
// 올바른 사용
a++
3. 제어 흐름 키워드( if, when, for 및 while)와 해당 여는 괄호 사이에 공백을 넣습니다.
제어 흐름 키워드와 여는 괄호 사이에 공백을 추가하여 흐름 제어 구문을 더 명확하게 만듭니다.
// 올바른 사용
if (condition) {
// ...
}
4. 기본 생성자 선언, 메서드 선언 또는 메서드 호출에서 여는 괄호 앞에 공백을 넣지 마십시오.
생성자 선언, 메서드 선언 또는 메서드 호출의 여는 괄호 앞에는 공백을 추가하지 않습니다.
// 올바른 사용
fun someFunction(parameter: Int) {
// ...
}
5. (, [, 뒤에 공백을 넣지 마십시오.
여는 괄호나 대괄호 앞에는 공백을 추가하지 않습니다.
// 올바른 사용
fun someFunction(parameter: Int) {
// ...
}
6. . 또는 ?. : 주위에 공백을 두지 마십시오.
멤버 접근( . ) 또는 세이프 콜( ?. ) 연산자 주위에는 공백을 추가하지 않습니다.
// 올바른 사용
val myList = listOf(1, 2, 3)
val result = foo.bar().filter { it > 2 }.joinToString().foo?.bar()
7. // 뒤에 공백을 넣으십시오.
주석( // ) 뒤에 공백을 추가하여 코드와 주석을 분리합니다.
// 올바른 사용
val value = 42 // This is a comment
8. 유형 매개변수를 지정하는 데 사용되는 꺾쇠 괄호 주위에 공백을 넣지 마십시오.
유형 매개변수를 지정하는 꺾쇠 괄호 주위에는 공백을 추가하지 않습니다.
// 올바른 사용
class Map<K, V> { /* ... */ }
9. : , :: 주위에 공백을 넣지 마십시오.
:: 타입 캐스팅 연산자( : )나 메서드 참조( :: ) 주위에는 공백을 추가하지 않습니다.
// 올바른 사용
val length = String::length
10. ? Null 허용 유형을 표시하는 데 사용되기 전에 공백을 넣지 마십시오.
Null 허용 유형을 표시할 때( ? ) 문자 뒤에 공백을 추가하지 않습니다.
// 올바른 사용
val nullableString: String?
콜론
다음과 같은 경우에는 앞에 공백을 넣으세요.
- 유형과 상위 유형을 구분하는 데 사용되는 경우에 공백을 넣어야 합니다.
- 슈퍼클래스 생성자나 같은 클래스의 다른 생성자에게 위임할 때 공백을 넣어야 합니다.
- object 키워드 뒤에 공백을 넣어야 합니다.
선언과 해당 유형을 구분할 때 앞에 공백을 넣으세요.
뒤에는 항상 공백을 두어야 합니다.
abstract class Foo<out T : Any> : IFoo {
abstract fun foo(a: Int): T
}
class FooImpl : Foo() {
constructor(x: String) : this(x) { /*...*/ }
val x = object : IFoo { /*...*/ }
}
2. 클래스 헤더, 수정자 순서, 주석, 파일 주석
3. 기능, 표현식 본문, 속성, 제어 흐름문, 메소드 호출, 체인된 호출
4. 람다, 후행 쉼표
공부하는 공돌이, 공공돌입니다🐻
@sheep1sik
'Android' 카테고리의 다른 글
[ Kotiln Code conventions ] 서식 지정(Formatting) 3 (2) | 2023.11.02 |
---|---|
[ Kotiln Code conventions ] 서식 지정(Formatting) 2 (2) | 2023.10.30 |
[ Kotlin Code conventions ] 명명규칙(Naming rules) (2) | 2023.10.29 |
[ Kotlin Code conventions ] 소스코드 구성(Source code organization) (1) | 2023.10.22 |
Kotlin 함수와 변수 (1) | 2023.10.19 |