Created
May 6, 2010 02:09
-
-
Save mwisnicki/391703 to your computer and use it in GitHub Desktop.
Pass by reference for Scala
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
// 'out' and 'inout' arguments for scala | |
object BasicExample { | |
// out param | |
def set(newvalue: Int, x: Int => Unit) { x(newvalue) } | |
// inout param | |
def inc(amount: Int, x: (Int, Int => Unit)) { x._2(x._1 + amount) } | |
} | |
// with wrapper classes | |
class OutP[T](set: T => Unit) { | |
def update(newvalue: T) = set(newvalue) | |
} | |
object OutP { | |
def apply[T](set: T => Unit) = new OutP(set) | |
} | |
class InOutP[T](get: T, set: T => Unit) extends OutP[T](set) { | |
def apply() = get | |
} | |
object InOutP { | |
def apply[T](get: T, set: T => Unit) = new InOutP[T](get, set) | |
} | |
object BetterExample { | |
def set(newvalue: Int, x: OutP[Int]) { x() = newvalue } | |
def inc(amount: Int, x: InOutP[Int]) = { x() += amount } | |
} | |
object Demo extends Application { | |
var x = 0 | |
println("BasicExample x = " + x) | |
BasicExample.set(9, x=_) | |
println("x = " + x) | |
BasicExample.inc(2, (x,x=_)) | |
println("x = " + x) | |
x = 0 | |
println("Better x = " + x) | |
BetterExample.set(9, OutP(x=_)) | |
println("x = " + x) | |
BetterExample.inc(2, InOutP(x,x=_)) | |
println("x = " + x) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment