TIL

아이템 47 인라인 클래스의 사용을 고려하라

코틀린 1.6부터는 value class로 명칭이 변경되었다.

inline class Name(private val value: String) { /* ... */ }
val name: Name = Name("Marcin")

// 컴파일 후
val name: String = "Marcin"

측정 단위를 표현할 때

interface Timer {
	fun callAfter(time: Int, callback: () -> Unit)
}
inline class Millis(val milliseconds: Int) { /* ... */ }

interface Timer {
	fun callAfter(timeMillis: Millis, callback: () -> Unit)
}

타입 오용으로 발생하는 문제를 막을 때

inline class StudentId(val studentId: Int)
inline class TeacherId(val teacherId: Int)
inline class SchoolId(val studentId: Int)

class Grades(
	val studentId: StudnetId,
	val teacherId: TeacherId,
	val schoolId: SchoolId,
)

인라인 클래스와 인터페이스

typealias

typealias ClickListener = (view: View, event: Event) -> Unit

class View {
	fun addClickListener(listener: ClickListener) { }
	// ...
}
typealias Seconds = Int
typealias Millis = Int

fun main() {
	val seconds: Seconds = 10
	val millis: Millis = seconds // 컴파일 에러가 발생하지 않는다.
}