Skip to content

Instantly share code, notes, and snippets.

@ae6rt
Created March 12, 2012 00:07
Show Gist options
  • Save ae6rt/2018778 to your computer and use it in GitHub Desktop.
Save ae6rt/2018778 to your computer and use it in GitHub Desktop.
Kotlin extension functions
package extfun
import java.util.List
import java.util.ArrayList
fun main(args : Array<String>) : Unit {
swapEm()
/*
Output is
[3, 2, 1]
[x, s, b]
*/
}
// Extension function on List<T>
fun <T> List<T>.swap(x : Int, y : Int) {
val tmp = this[x]
this[x] = this[y]
this[y] = tmp
}
fun swapEm() {
val l = ArrayList<Int>()
l.add(1)
l.add(2)
l.add(3)
l.swap(0, 2)
println(l)
val s = ArrayList<String>()
s.add("s")
s.add("x")
s.add("b")
s.swap(0, 1)
println(s)
}
Reference: http://confluence.jetbrains.net/display/Kotlin/Extension+functions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment