《scala cookBook》Chapter2

C:\Users\enmonster>scala
Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_161).
Type in expressions for evaluation. Or try :help.

scala> Short.MinValue
res0: Short = -32768

scala> Short.MaxValue
res1: Short = 32767

scala> @throws(classOf[NumberFormatException])
     | def toInt(s:String) = s.toInt
toInt: (s: String)Int

scala> val a = 10
a: Int = 10

scala> val b = a.to//按下tab键,可自动显示可用方法
to               toByte   toDegrees   toFloat       toInt    toOctalString   toShort
toBinaryString   toChar   toDouble    toHexString   toLong   toRadians       toString

scala> val b = a.to

def to(end: Int,step: Int): scala.collection.immutable.Range.Inclusive
def to(end: Int): scala.collection.immutable.Range.Inclusive
def to(end: Double,step: Double): scala.collection.immutable.NumericRange.Inclusive[Double]
def to(end: Float): Range.Partial[Float,scala.collection.immutable.NumericRange[Float]]
def to(end: Long): scala.collection.immutable.NumericRange.Inclusive[Long]
def to(end: Float,step: Float): scala.collection.immutable.NumericRange.Inclusive[Float]
def to(end: Long,step: Long): scala.collection.immutable.NumericRange.Inclusive[Long]
def to(end: Double): Range.Partial[Double,scala.collection.immutable.NumericRange[Double]]

scala> val b = a.toLong//转换为Long
b: Long = 10

scala> val c = a.//tab键显示可用方法
!=   <=          ceil          isInfinity      isWhole      toBinaryString   toOctalString
%    ==          compare       isNaN           longValue    toByte           toRadians
&    >           compareTo     isNegInfinity   max          toChar           toShort
*    >=          doubleValue   isPosInfinity   min          toDegrees        unary_+
+    >>          floatValue    isValidByte     round        toDouble         unary_-
-    >>>         floor         isValidChar     self         toFloat          unary_~
/    ^           getClass      isValidInt      shortValue   toHexString      underlying
<    abs         intValue      isValidLong     signum       toInt            until
<<   byteValue   isInfinite    isValidShort    to           toLong           |

scala> val a = 1000l//声明一个Long型变量
a: Long = 1000

scala> a.is
isInfinite   isInstanceOf   isNegInfinity   isValidByte   isValidInt    isValidShort
isInfinity   isNaN          isPosInfinity   isValidChar   isValidLong   isWhole

scala> a.isValidByte//转换成Byte类型是否合法?
res3: Boolean = false

scala> a.isValidInt//转换成Int类型是否合法?
res4: Boolean = true

scala> val a :Byte = 0
a: Byte = 0

scala> val a = 0x20//16进制
a: Int = 32

scala> val s = "Dave"
s: String = Dave

scala> val p = s:Object//what's meaning?
p: Object = Dave

scala> var a= 1//var 而不是val
a: Int = 1

scala> a +=1//a的值已经发生了改变

scala> a.println
<console>:13: error: value println is not a member of Int
       a.println
         ^

scala> println(a)
2

scala> val r = scala.util.Random//生成一个随机数
r: util.Random.type = scala.util.Random$@280c3dc0

scala> r.nextInt(1)//生成一个0-1范围内的随机数
res10: Int = 0

scala> r.nextInt(10)//生成一个0-10范围内的随机数
res12: Int = 4

scala> r.nextPrintableChar//生成一个可打印的字符
res38: Char = /

scala> r.nextPrintableChar
res39: Char = L

scala> r.
alphanumeric         nextBytes    nextGaussian   nextPrintableChar   setSeed
javaRandomToRandom   nextDouble   nextInt        nextString          shuffle
nextBoolean          nextFloat    nextLong       self

scala> val range = 0 to r.nextInt(10)//根据随机数的功能生成一个range
range: scala.collection.immutable.Range.Inclusive = Range(0, 1, 2, 3)

scala> for(i <- 0 to r.nextInt(10)) yield i*2
res43: scala.collection.immutable.IndexedSeq[Int] = Vector(0, 2, 4)

scala> for(i <- 0 to r.nextInt(10)) yield r.nextPrintableChar
res44: scala.collection.immutable.IndexedSeq[Char] = Vector(@)

scala> val r = 1 to 10 by 5//增幅为5
r: scala.collection.immutable.Range = Range(1, 6)

scala> val x = 1 to 5
x: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5)

scala> val x = 1 to 5 toArray
warning: there was one feature warning; re-run with -feature for details
x: Array[Int] = Array(1, 2, 3, 4, 5)

scala> 1.to(10)
res46: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> scala.math.Pi//数学函数
res47: Double = 3.141592653589793

scala> val pi = scala.math.Pi
pi: Double = 3.141592653589793

scala> f("$pi%1.2f")//不用括号
<console>:12: error: not found: value f
       f("$pi%1.2f")
       ^

scala> println(f"$pi%1.2f")//格式化输出
3.14

scala> f"$pi%1.2f"
res51: String = 3.14

scala> val a = Array("apple","banana","orange")
a: Array[String] = Array(apple, banana, orange)

scala> val names = Map("fname"->"Robert","lname"->"Goren")
names: scala.collection.immutable.Map[String,String] = Map(fname -> Robert, lname -> Goren)

scala> for((k,v) <- names)
     | println(s"key:$k,value:$v")
key:fname,value:Robert
key:lname,value:Goren

scala> scalac -Xprint:parse C:\Users\enmonster\Main.scala//路径正确,但是编译出错
<console>:1: error: identifier expected but '.' found.
scalac -Xprint:parse C:\Users\enmonster\Main.scala
                                            ^
scala> :quit

C:\Users\enmonster>scalac -Xprint:parse C:\Users\enmonster\Main.scala//直接使用scalac命令
[[syntax trees at end of                    parser]] // Main.scala
package <empty> {
  class Main extends scala.AnyRef {
    def <init>() = {
      super.<init>();
      ()
    };
    1.to(10).foreach(((i) => println(i)))
  }
}


C:\Users\enmonster>scalac -Xprint:all C:\Users\enmonster\Main.scala
[[syntax trees at end of                    parser]] // Main.scala
package <empty> {
  class Main extends scala.AnyRef {
    def <init>() = {
      super.<init>();
      ()
    };
    1.to(10).foreach(((i) => println(i)))
  }
}

[[syntax trees at end of                     namer]] // Main.scala: tree is unchanged since parser
[[syntax trees at end of            packageobjects]] // Main.scala: tree is unchanged since parser
[[syntax trees at end of                     typer]] // Main.scala
package <empty> {
  class Main extends scala.AnyRef {
    def <init>(): Main = {
      Main.super.<init>();
      ()
    };
    scala.this.Predef.intWrapper(1).to(10).foreach[Unit](((i: Int) => scala.this.Predef.println(i)))
  }
}

[[syntax trees at end of                    patmat]] // Main.scala: tree is unchanged since typer
[[syntax trees at end of            superaccessors]] // Main.scala: tree is unchanged since typer
[[syntax trees at end of                extmethods]] // Main.scala: tree is unchanged since typer
[[syntax trees at end of                   pickler]] // Main.scala: tree is unchanged since typer
[[syntax trees at end of                 refchecks]] // Main.scala: tree is unchanged since typer
[[syntax trees at end of                   uncurry]] // Main.scala
package <empty> {
  class Main extends Object {
    def <init>(): Main = {
      Main.super.<init>();
      ()
    };
    scala.this.Predef.intWrapper(1).to(10).foreach[Unit]({
      @SerialVersionUID(value = 0) final <synthetic> class $anonfun extends scala.runtime.AbstractFunction1[Int,Unit] with Serializable {
        def <init>(): <$anon: Int => Unit> = {
          $anonfun.super.<init>();
          ()
        };
        final def apply(i: Int): Unit = scala.this.Predef.println(i)
      };
      (new <$anon: Int => Unit>(): Int => Unit)
    })
  }
}

[[syntax trees at end of                 tailcalls]] // Main.scala: tree is unchanged since uncurry
[[syntax trees at end of                specialize]] // Main.scala
package <empty> {
  class Main extends Object {
    def <init>(): Main = {
      Main.super.<init>();
      ()
    };
    scala.this.Predef.intWrapper(1).to(10).foreach$mVc$sp({
      @SerialVersionUID(value = 0) final <synthetic> class $anonfun extends scala.runtime.AbstractFunction1$mcVI$sp with Serializable {
        def <init>(): <$anon: Int => Unit> = {
          $anonfun.super.<init>();
          ()
        };
        final def apply(i: Int): Unit = $anonfun.this.apply$mcVI$sp(i);
        <specialized> def apply$mcVI$sp(i: Int): Unit = scala.this.Predef.println(i)
      };
      (new <$anon: Int => Unit>(): Int => Unit)
    })
  }
}

[[syntax trees at end of             explicitouter]] // Main.scala
package <empty> {
  class Main extends Object {
    def <init>(): Main = {
      Main.super.<init>();
      ()
    };
    scala.this.Predef.intWrapper(1).to(10).foreach$mVc$sp({
      @SerialVersionUID(value = 0) final <synthetic> class $anonfun extends scala.runtime.AbstractFunction1$mcVI$sp with Serializable {
        def <init>($outer: Main.this.type): <$anon: Int => Unit> = {
          $anonfun.super.<init>();
          ()
        };
        final def apply(i: Int): Unit = $anonfun.this.apply$mcVI$sp(i);
        <specialized> def apply$mcVI$sp(i: Int): Unit = scala.this.Predef.println(i);
        <synthetic> <paramaccessor> <artifact> private[this] val $outer: Main.this.type = _;
        <synthetic> <stable> <artifact> def $outer(): Main.this.type = $anonfun.this.$outer
      };
      (new <$anon: Int => Unit>(Main.this): Int => Unit)
    })
  }
}

[[syntax trees at end of                   erasure]] // Main.scala
package <empty> {
  class Main extends Object {
    def <init>(): Main = {
      Main.super.<init>();
      ()
    };
    RichInt.this.to$extension0(scala.this.Predef.intWrapper(1), 10).foreach$mVc$sp({
      @SerialVersionUID(value = 0) final <synthetic> class $anonfun extends scala.runtime.AbstractFunction1$mcVI$sp with Serializable {
        def <init>($outer: Main): <$anon: Function1> = {
          $anonfun.super.<init>();
          ()
        };
        final def apply(i: Int): Unit = $anonfun.this.apply$mcVI$sp(i);
        <specialized> def apply$mcVI$sp(i: Int): Unit = scala.this.Predef.println(scala.Int.box(i));
        <synthetic> <paramaccessor> <artifact> private[this] val $outer: Main = _;
        <synthetic> <stable> <artifact> def $outer(): Main = $anonfun.this.$outer;
        final <bridge> <artifact> def apply(v1: Object): Object = {
          $anonfun.this.apply(unbox(v1));
          scala.runtime.BoxedUnit.UNIT
        }
      };
      (new <$anon: Function1>(Main.this): Function1)
    })
  }
}

[[syntax trees at end of               posterasure]] // Main.scala: tree is unchanged since erasure
[[syntax trees at end of                  lazyvals]] // Main.scala: tree is unchanged since erasure
[[syntax trees at end of                lambdalift]] // Main.scala
package <empty> {
  class Main extends Object {
    def <init>(): Main = {
      Main.super.<init>();
      ()
    };
    RichInt.this.to$extension0(scala.this.Predef.intWrapper(1), 10).foreach$mVc$sp({
      (new <$anon: Function1>(Main.this): Function1)
    });
    @SerialVersionUID(value = 0) final <synthetic> class $anonfun$1 extends scala.runtime.AbstractFunction1$mcVI$sp with Serializable {
      def <init>($outer: Main): <$anon: Function1> = {
        $anonfun$1.super.<init>();
        ()
      };
      final def apply(i: Int): Unit = $anonfun$1.this.apply$mcVI$sp(i);
      <specialized> def apply$mcVI$sp(i: Int): Unit = scala.this.Predef.println(scala.Int.box(i));
      <synthetic> <paramaccessor> <artifact> private[this] val $outer: Main = _;
      <synthetic> <stable> <artifact> def $outer(): Main = $anonfun$1.this.$outer;
      final <bridge> <artifact> def apply(v1: Object): Object = {
        $anonfun$1.this.apply(scala.Int.unbox(v1));
        scala.runtime.BoxedUnit.UNIT
      }
    }
  }
}

[[syntax trees at end of              constructors]] // Main.scala
package <empty> {
  class Main extends Object {
    @SerialVersionUID(value = 0) final <synthetic> class $anonfun$1 extends scala.runtime.AbstractFunction1$mcVI$sp with Serializable {
      final def apply(i: Int): Unit = $anonfun$1.this.apply$mcVI$sp(i);
      <specialized> def apply$mcVI$sp(i: Int): Unit = scala.this.Predef.println(scala.Int.box(i));
      final <bridge> <artifact> def apply(v1: Object): Object = {
        $anonfun$1.this.apply(scala.Int.unbox(v1));
        scala.runtime.BoxedUnit.UNIT
      };
      def <init>($outer: Main): <$anon: Function1> = {
        $anonfun$1.super.<init>();
        ()
      }
    };
    def <init>(): Main = {
      Main.super.<init>();
      RichInt.this.to$extension0(scala.this.Predef.intWrapper(1), 10).foreach$mVc$sp({
        (new <$anon: Function1>(Main.this): Function1)
      });
      ()
    }
  }
}

[[syntax trees at end of                   flatten]] // Main.scala
package <empty> {
  class Main extends Object {
    def <init>(): Main = {
      Main.super.<init>();
      RichInt.this.to$extension0(scala.this.Predef.intWrapper(1), 10).foreach$mVc$sp({
        (new <$anon: Function1>(Main.this): Function1)
      });
      ()
    }
  };
  @SerialVersionUID(value = 0) final <synthetic> class anonfun$1 extends scala.runtime.AbstractFunction1$mcVI$sp with Serializable {
    final def apply(i: Int): Unit = anonfun$1.this.apply$mcVI$sp(i);
    <specialized> def apply$mcVI$sp(i: Int): Unit = scala.this.Predef.println(scala.Int.box(i));
    final <bridge> <artifact> def apply(v1: Object): Object = {
      anonfun$1.this.apply(scala.Int.unbox(v1));
      scala.runtime.BoxedUnit.UNIT
    };
    def <init>($outer: Main): <$anon: Function1> = {
      anonfun$1.super.<init>();
      ()
    }
  }
}

[[syntax trees at end of                     mixin]] // Main.scala: tree is unchanged since flatten
[[syntax trees at end of                   cleanup]] // Main.scala: tree is unchanged since flatten
[[syntax trees at end of                delambdafy]] // Main.scala: tree is unchanged since flatten
[[syntax trees at end of                     icode]] // Main.scala: tree is unchanged since flatten
[[syntax trees at end of                       jvm]] // Main.scala: tree is unchanged since flatten


C:\Users\enmonster>scala
Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_161).
Type in expressions for evaluation. Or try :help.


scala> for(i <- 1 to 2;j <- 1 to 2)//模拟两层循环
     | println(s"i= $i,j = $j")
i= 1,j = 1
i= 1,j = 2
i= 2,j = 1
i= 2,j = 2

scala> val array = Array.ofDim[Int](2,2)
array: Array[Array[Int]] = Array(Array(0, 0), Array(0, 0))

scala> for(i <- 1 to 10 if i%2 ==0)//for循环中 书写if表达式
     | println(i)
2
4
6
8
10

scala> class TestConstructor(val firstName:String,val lastName:String) {
     |   println("the constructor begins")
     |   private val HOME= System.getProperty("user.home")
     |   val age = 0
     |   override def toString = s"$firstName $lastName is $age years old"
     |   def printHome{println(s"HOME = $HOME")}
     |   def printFullName{println(this)}//uses toString
     |   printHome
     |   printFullName
     |   println("Still in the constructor")
     | }
defined class TestConstructor

scala> val p = new TestConstructor("Lawson","Little")
the constructor begins
HOME = C:\Users\enmonster
Lawson Little is 0 years old
Still in the constructor
p: TestConstructor = Lawson Little is 0 years old

scala> class Person(var name:String)
defined class Person

scala> val p = new Person("LittleLawson ,Anhui")
p: Person = Person@68ed3f30

scala> p.name
res4: String = LittleLawson ,Anhui

scala> val p = new Person("LittleLawson ")
p: Person = Person@50448409

scala> p.name
res5: String = "LittleLawson "

scala> p.name = "ltt"//var值可修改
p.name: String = ltt