【2019-05-23】scala的层级

2019-05-23  本文已影响0人  BigBigFlower
Scala类层级

层级的顶端是Any类,定义了下列的方法 :

final def ==(that: Any): Boolean
  final def !=(that: Any): Boolean
  def equals(that: Any): Boolean
  def hashCode: Int
  def toString: String

Scala里每个类都继承自通用的名为Any的超类,因为所有的类都是Any的子类。所以定义在Any中的方法就是“共同的”方法:他们可以将任何对象调用。

42 max 43
//res5: Int = 43
42.hashCode
//res6: Int = 42
42.toString
//res7: String = 42
1 to 5
//res8: scala.collection.immutable.Range.Inclusive = Range 1 to 5
1 until 5
//res9: scala.collection.immutable.Range = Range 1 until 5
(-3).abs
//res10: Int = 3
val a = 1 until 5 
//a: scala.collection.immutable.Range = Range 1 until 5
a.length
//res18: Int = 4
while (i<a.length){
      print(a(i))
      i+=1
      }
//1234

原始类型实现

def isEqual(x: Int, y: Int) = x == y
//isEqual: (x: Int, y: Int)Boolean
isEqual(3,5)
//res5: Boolean = false
def isEqual(x: Any, y: Any) = x == y
//isEqual:(x: Any, y: Any)Boolean
isEqual('a','a')
//res8: Boolean = true

底层类型
scala以与Java同样的方式存储整数:把它当作32位的字。

object Ex3 {
  def divide(x: Int, y: Int): Int = 
    if (y != 0) x / y 
    else error("can't divide by zero")

  def main(args: Array[String]) {
    val d1 = divide(4, 2)
    println("d1 [" + d1 + "]")

    try {
      val d2 = divide(4, 0)
      println("d2 [" + d2 + "]")
    } catch {
      case ex: RuntimeException => println("ex [" + ex + "]")
    }
  }
}
上一篇下一篇

猜你喜欢

热点阅读