Created
March 12, 2012 00:07
-
-
Save ae6rt/2018778 to your computer and use it in GitHub Desktop.
Kotlin extension functions
This file contains hidden or 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
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