
31DaysOfKotlin 21~
매일 정리하여 이전 글에 수정으로 글을 올리고 있는데,
또 수정이 막혔다.
이전 글 링크
Day 21. Operator overloading
- https://kotlinlang.org/docs/reference/operator-overloading.html#operator-overloading
- https://github.com/android/android-ktx/blob/master/src/main/java/androidx/core/text/SpannableString.kt#L32
연산자 오버로딩을 사용하여 Path, Range, SpannableStrings 와 같은 객체에 연산자를 사용한 연산을 할 수 있다.
- plus, minus, times, div...
/** Adds a span to the entire text **/
inline operator fun Spannable.plusAssign(span: Any) =
setSpan(span, 0, length, SPAN_INCLUSIVE_EXCLUSIVE)
// Use it like this
val spannable = "Eureka!!!!".toSpannalbe()
spannable += StyleSpan(BOLD) // Make the text bold with +=
spannable += UnderlineSpan() // Make the text underline with +=
Day 22. Top-level method, property
코틀린은 Java와 달리 파일에 함수와 프로퍼티를 선언할 수 있다. 파일에 선언된 함수와 프로퍼티는 static으로 컴파일 된다.
// Define a top-level function that creates a DataBinding Adapter for a RecyclerView
@BindingAdapter("userItems")
fun userItems(recyclerView: RecyclerView, list: List<User>?) {
// update the RecyclerView with the new list
}
// Define a top-level property for Room database
private const val DATABASE_NAME = "MyDatabase.db"
private fun makeDatabase(context: Context): MyDatabase {
return Room.databaseBuilder(
context,
MyDatabase::class.java,
DATABASE_NAME).build()
}
Day 23. Custom Iterator
- https://kotlinlang.org/docs/reference/control-flow.html#for-loops
- https://github.com/android/android-ktx/blob/master/src/main/java/androidx/core/view/ViewGroup.kt#L66
operator 키워드를 사용하여 iterator()를 정의하고, 이를 루프에서 사용할 수 있다.
// Example from Android KTX
for (view in viewGroup) { }
for (key in sparseArray.keyIterator()) { }
// Your project
// add an iterator to a Watoerfall
operator fun Waterfall.iterator() = // ... extend waterfall to have iterator
for (items in waterfall) { } // now waterfall can iterate!
Day 24. ContentValue
Android KTX의 contentValuesOf 함수로 쉽게 ContentValue를 만들 수 있다. (이를 다른데 적용할 수 있을지 고민해보자)
val contentValues = contentValuesOf(
"KEY_INT" to 1,
"KEY_LONG" to 2L,
"KEY_BOOLEAN" to true,
"KEY_NULL" to null
)
Day 25. Type safe builder
- https://kotlinlang.org/docs/reference/lambdas.html#function-literals-with-receiver
- https://kotlinlang.org/docs/reference/type-safe-builders.html
kotlin으로 DSL을 만들수 있다. 위 링크를 참고하자.
html {
head {
title {+"This is Kotlin!"}
}
body {
h1 {+"A DSL defined in Kotlin!"}
p {+"It's rather"
b {+"bold."}
+"don't you think?"
}
}
}
Spek는 코틀린 DSL로 만들어진 테스팅 라이브러리다. (단순히 예제 하나만 봐서는 잘 모르겠다.)
@RunWith(JUnitPlatform::class)
class MyTest : Spek({
val subject = Subject()
given("it's on fire") {
subject.lightAFire()
if("should be burning") {
assertTrue(subject.isBurning())
}
}
})
Gradle에서도 Kotlin DSL을 사용하여 빌드 스크립트를 작성할 수 있다.
Anko는 안드로이드용 Kotlin DSL 라이브러리이다.
frameLayout {
button("Light a fire") {
onLick {
lightAFire()
}
}
}
Day 26. Bundle with Android KTX
Android KTX로 번들 생성하는 방법. (ContentValues와 비슷)
val bundle = bundleOf(
"KEY_INT" to 1,
"KEY_LONG" to 2L,
"KEY_BOOLEAN" to true,
"KEY_NULL" to null,
"KEY_ARRAY" to arrayOf(1,2)
)
Leave 31DaysOfKotlin 21~ to:
Read more #kr posts
Best Posts From kkumot
We have not curated any of kkumot's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.