ArrayList.withSize(3)
inline
으로 만들 수 있으며 파라미터들을 reified
로 만들 수 있다.companion
객체를 사용하는 것이다.interface MyList<T> {
// ...
companion object {
fun <T> of(vararg elements: T): MyList<T>? {
// ...
}
}
// ...
}
companion
객체 멤버를 단순히 정적 멤버처럼 다루는 경우가 많은데 사실 더 많은 기능을 가지고 있다.companion
객체는 인터페이스를 구현할 수 있고 클래스를 상속받을 수도 있다.abstract class ActivityFactory {
abstract fun getIntent(context: Context): Intent
fun start(context: Context) { /* */ }
fun startForResult(activity: Activity, requestCode: Int) { /* */ }
}
class MainActivity: AppCompatActivity() {
// ...
companion object: ActivityFactory() {
override fun getIntent(context: Context): Intent =
Intent(context, MainActivity::class.java)
}
}
// 사용
val intent = MainActivity.getIntent(context)
MainActivity.start(context)
MainActivity.startForResult(activity, resultCode)
companion
객체 팩토리는 값을 가질 수 있기에 캐싱을 구현하거나 가짜 객체를 생성할 수도 있다.companion
객체가 컨텍스트 구분을 목적으로 CoroutineContext.Key
인터페이스를 구현하고 있다.companion
객체를 직접 수정할 수 없을 땐 확장 함수를 만들어 팩토리 함수를 만들 수 있다.
fun Tool.Companion.createBigTool( /*...*/ ): BigTool {
// ...
}
listOf()
, setOf()
, mapOf()
public
톱레벨 함수는 모든 곳에서 사용 가능하기에 IDE의 팁을 복잡하게 만드는 단점이 있다.A() // 생성자
a() // 톱레벨 함수
List
, MutableList
는 인터페이스이기에 생성자를 가질 수 없지만 아래 함수가 가능하다.List(4) { "User$it" } // [User0, User1, User2, User3]
public inline fun <T> List(size: Int, init: (index: Int) -> T): List<T>
= /* ... */
reified
타입 아규먼트를 갖게 하고 싶을 때