Intro to scala in one page Subscribe Pub

This was the original crash course to scala in one page that I created for - it tried to capture as many notable features in one page as possible... maybe you find it interesting.

//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 ...

//move cursor to following line and issue "run line"
add (1+2, 8/4) // see the implicit conversion?

//move cursor to end of following line and press ctrl+space for content assist

It obviously doesn't touch the type system and many other important parts of scala.

Was this useful?    

By: Razie | 2017-05-29 .. 2017-06-01 | Tags: post

See more in: Cool Scala Subscribe

Viewed 186 times ( | Print ) this page.

You need to log in to post a comment!