Created
July 24, 2012 15:24
-
-
Save razie/3170650 to your computer and use it in GitHub Desktop.
crash course to scala - looking for better ideas
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
//crash-course into scala: select the following defs and issue "run selection" | |
class Num (val i:Int) { | |
def + (other:Num) = new Num (this.i + other.i) // operators | |
override def toString : String = "Numero " + i.toString // inherit Java methods | |
override def equals (other:Any) = other match { // or override them | |
case n:Num => n.i == i | |
case _ => false // wildcard serves like a default case | |
} | |
} | |
object Num { // companion object contains statics for Num | |
def apply (i:Int) = new Num (i) // this lets you do Num(3) instead of new Num(3) | |
def valueOf (s:String) = new Num (s.toInt) | |
} | |
implicit def toNum (i:Int) = Num (i) // this makes the conversion implicit | |
def add (i:Num*) = { // variable argument list | |
val ss = "12344" // type inferred as String | |
var ii = Num(0) | |
for (k <- i) ii = ii + k // boo hoo - the way of the java... | |
assert (ii == i.foldLeft (Num(0)) (_+_)) // woo hoo - the way of the lambda ... | |
ii | |
} | |
//move cursor to following line and issue "run line" | |
add (1+2, 8/4) // see the implicit conversion? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment