code snippet-01
more https://github.com/yuqingwang15/scala-coding
01break 用法
// (x:Int, y:Int) => x+y import scala.util.control.Breaks._ object test { def main(args:Array[String]){ println("hello test") breakable{ for(i<-0 to 10){ if(i==5) break println(i) } } println(test2) } def test2():Int={ return 1 } } //breakable
02 Symbol定义
// `x final case class Symbol private (name:String){ override def toString(name:String):String = "`" + name } /* see the toString(name:String) as a funcname and the return type is string give the funcname value : "`" + name override just point out that this func have some relation with others class is a object containing a func-object and a parameter */
03多行输出
"""the present string
spans three
lines."""
04 case
//null scala.Null //与每个引用类型兼容。它表示引用一个特殊的“null”对象的参考值。 //abstract works with extends //case works with extends abstract class , sons of abstract class //class has parameters with types //object JNull abstract class JSON case class JSeq(elems: List[JSON]) extends JSON case class JNum(elems: Double) extends JSON case class JStr(elems: String) extends JSON case class JBool(elems: Boolean) extends JSON case class JObj(bingdings: Map[String, JSON]) extends JSON case object JNull extends JSON type JBinding = (String , JSON) // a match{case ab ; case ac ..} //=> do what,instructions = is what,defination // class tjson { def show(json :JSON) :String= json match{ case JNum(num) => num.toString case JStr(str) => "\""+str +"\"" case JBool(b) => b.toString case JSeq(seq)=>"["+ (seq map show mkString ",") +"]" // binding is what :map from (k,v) to String case JObj(bindings) => val obj = bindings map{ case (key ,value) =>"\"" +key+"\":" + show(value) } case JNull =>"null" }
05单例
import java.io_ class Point(val xc:Int,val yc:Int){ var x:Int = xc var y:Int = yc //val ->var def move(dx:Int, dy:Int) { x = dx+x y = dy+y } } object Demo{ def main(args:Array[String]){ val point = new Point(10,20) printPoint def printPoint{ println("Point x location:" + point.x) } } }
06loop
object Run { implicit class IntTimes(x: Int) { def times [A](f: =>A): Unit = { def loop(current: Int): Unit = if(current > 0){ f loop(current - 1) } loop(x) } } } import Run._ object Demo { def main(args: Array[String]) { 4 times println("hello") } }
From satrys,
Kristen wang