Skip to content

Instantly share code, notes, and snippets.

View travisdachi's full-sized avatar
🖖
Live long and prosper

Travis P travisdachi

🖖
Live long and prosper
View GitHub Profile
fun attack(target: Target): Unit {}
fun attack(target: Target) {}
// fun <funName>(<parameterName>: <parameterType>): <returnType> [ = <singleExpression>]
fun fetchSomething(someId: String, callback: (Something) -> Unit) {
val something = ...
callback(something)
}
fetchSomething("anotherId", { something ->
something.doSomething()
})
fetchSomething("someOtherId") {
//Java version
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//do something
}
});
//Kotlin version
view.setOnClickListener {
class SomeActivity : Activity() {
val f: Foo by lazy { createFoo() } // put your initialization block here
fun onCreate(bundle: Bundle?) {
f.foo() // f will be created here and it's a val so you can't change it
f // or you can call a getter just to initialize it
}
fun createFoo() = Foo(this)
// this is useful when you need a context after the activity is created
data class Present(var id: String = "", var toy: String = "", var kid: String = "", var given: Boolean = false)
val list: MutableList<Present> = mutableListOf(
Present("p0", "Dinosaur Figure", "Ralph", true),
Present("p1", "Teddy Bear", "Ginger"),
Present("p2", "Teddy Bear", "Cherry")
)
list[3] = Present("p3", "Pony Plush", "Cherry")
for (p in list) println(p)
list.forEach { println(it) }
// Taken from Kotlin standard library
public inline fun <T> Iterable<T>.forEach(action: (T) -> Unit): Unit {
for (element in this) action(element)
}
for (i in 0..list.size - 1) println("list[$i]: ${list[i]}")
for (i in list.indices) println("list[$i]: ${list[i]}")
val filtrate: List<Present> = list.filter { it.kid == "Cherry" }
// filtrate contains 2 elements which are p2 and p3
val kids: List<String> = list.map { it.kid }
// kids = [Ralph, Ginger, Cherry, Cherry]
val g: Map<String, List<Present>> = list.groupBy { it.kid }
/*
{
Ralph=[Present(id=p0, toy=Dinosaur Figure, kid=Ralph, given=true)],
Ginger=[Present(id=p1, toy=Teddy Bear, kid=Ginger, given=false)],
Cherry=[Present(id=p2, toy=Teddy Bear, kid=Cherry, given=false), Present(id=p3, toy=Pony Plush, kid=Cherry, given=false)]
}
*/
val m: MutableMap<String, String> = mutableMapOf(
Pair("one", "1"),
"two" to "2"
)
println(m["two"])
m["three"] = "3"
m.forEach { println("${it.key}: ${it.value}") }