Skip to content

Instantly share code, notes, and snippets.

@ice1000
Created August 20, 2016 00:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ice1000/16d851883e0ac61f905cbb891d20a155 to your computer and use it in GitHub Desktop.
Save ice1000/16d851883e0ac61f905cbb891d20a155 to your computer and use it in GitHub Desktop.
Some interesting language extension in kotlin
package org.frice.game.utils.kotlin
/**
* Kotlin language extension
* for Kotlin only
*
*
* Created by ice1000 on 2016/8/17.
* @author ice1000
* @since v0.3.2
*/
inline fun <T> T.loop(block: T.() -> Unit): T {
while (true) block.invoke(this)
}
inline fun <T> T.loop(count: Int, block: T.(Int) -> Unit): T {
for (index in 0..count - 1) block.invoke(this, index)
return this
}
inline fun <T> T.loopIf(condition: () -> Boolean, block: T.() -> Unit): T {
while (true) if (condition.invoke()) block.invoke(this)
}
inline fun <T> T.forceRun(block: T.() -> Unit): T {
try {
block.invoke(this)
} catch (e: Throwable) {
}
return this
}
inline fun <T> T.forceGet(default: Any, block: T.() -> Any): Any {
return try {
block.invoke(this)
} catch (e: Throwable) {
default
}
}
/**
* if there's exception, it will exit
*/
inline fun <T> T.forceLoop(block: T.() -> Unit) = forceRun { loop(block) }
fun <T> T.pause(length: Int) = pause(length.toLong())
fun <T> T.pause(length: Double) = pause(length.toLong())
fun <T> T.pause(length: Long): T {
Thread.sleep(length)
return this
}
/**
* an anko-like async block
*/
inline fun <T> T.async(crossinline block: T.() -> Unit): T {
Thread({ block.invoke(this) }).start()
return this
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment