Created
January 23, 2018 08:04
-
-
Save PrashamTrivedi/ed02e991a1340ee2d5fcaf38a7981658 to your computer and use it in GitHub Desktop.
Handle cursor by delegates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
inline fun <T> Cursor.delegate(key: String? = null, | |
crossinline getter: Cursor.(Int) -> T): ReadOnlyProperty<Any?, T> { | |
return object : ReadOnlyProperty<Any?, T> { | |
override fun getValue(thisRef: Any?, property: KProperty<*>): T { | |
val s = key ?: property.name | |
return getter(getColumnIndex(s)) | |
} | |
} | |
} | |
fun Cursor.int(key: String? = null) = delegate(key = key, getter = Cursor::getInt) | |
fun Cursor.string(key: String? = null) = delegate(key = key, getter = Cursor::getString) | |
fun Cursor.boolean(key: String? = null) = delegate(key = key, getter = Cursor::getBoolean) | |
fun Cursor.double(key: String? = null) = delegate(key = key, getter = Cursor::getDouble) | |
fun Cursor.long(key: String? = null) = delegate(key = key, getter = Cursor::getLong) | |
fun Cursor.byteArray(key: String? = null) = delegate(key = key, getter = Cursor::getBlob) | |
fun Cursor.float(key: String? = null) = delegate(key = key, getter = Cursor::getFloat) | |
fun Cursor.short(key: String? = null) = delegate(key = key, getter = Cursor::getShort) | |
fun Cursor.getBoolean(columnIndex:Int): Boolean = getInt(columnIndex)!=0 | |
//Additional method to reduce boilerplate | |
fun Cursor?.readCursor(cursorReadFun: (Cursor) -> Unit) { | |
this?.let { | |
moveToFirst() | |
do { | |
cursorReadFun(it) | |
} while (moveToNext()) | |
} | |
} | |
//Full Example | |
cursor.readCursor{ | |
val doubleProperty by cursor.double("doubleProperty") | |
val intProperty by cursor.int("intProperty") | |
val stringProperty by cursor.string("stringProperty") | |
val booleanProperty by cursor.boolean("booleanProperty") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think
fun Cursor?.readCursor
should be inline