【2019-05-23】scala的層級

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 + "]")
    }
  }
}
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容