01.Any / Nothing / Option[T]

Scala 可將任意非容器類型引用賦給 Any, Any 為所有 Scala 類型的基/超類. 也是一個抽象類, 無法被實例化.



scala.Any 二大子類系統



  • AnyRef
    • 充當映射 Java 基本類型的父類
    • 無額外的方法
  • AnyVal
    • 所有參考類型的父類, 相當於且直接映射成 java.lang.Object
    • 包含方法
      • java.lang.Object 的方法集


scala.Any


abstract class Any

Class Any is the root of the Scala class hierarchy. Every class in a Scala execution environment inherits directly or indirectly from this class. Class Any has two direct subclasses: AnyRef and AnyVal.

Direct Known Subclasses:
Nothing, AnyRef, AnyVal


  1. 類別 Any 不可被實例化(Instance)
  2. 類別 Any 是 Scala 類別階層的根/最頂層類別, 不等同於 java.lang.Object .
  3. 任何類別在 Scala 執行環境中直接或間接繼承來自類別 Any .
  4. 類別 Any 擁有二個直接的子類別:
    1. AnyRef, 以 reference 參考指標至 Heap 為特質的根類別
    2. AnyVal, 俱不變性特質的類別根類別

Methods of Any


Any 身上相對於 java.lang.Object 的11個方法, 只有7個, 且僅 equals, hashCode, toString 三者與之相同, 目的也大致一樣, 其它如 clone, finalize, notify, notifyAll, wait 等加以惕除, 並增加純 OO 體系根類別最應該俱備的核心方法,

不可被覆寫 @Override 的二個判斷用方法

final def ==(arg0: Any): Boolean
final def !=(arg0: Any): Boolean


def equals(arg0: Any): Boolean
def hashCode: Int
def toString: String


final def asInstanceOf[T0]: T0
final def isInstanceOf[T0]: Boolena



scala.Nothing


Nothing 是Scala 所有 class 的最底層子類別, 只要是無參數化的容器都是 Nothing 的容器, 任何有意義類型實例都不可被附加到該容器類別中.


Nothing 是抽象的, 無法被實例化, 純粹是為了協助類型推斷而存在

scala.runtime.Nothing$

為所有類的最終子類, 這意謂著它可以被替換成任何事物!


object None extends Option[Nothing] with Product

This case object represents non-existent values.

source: Option.scala
    version 
  1. 1.0, 16/07/2003

    authors: 
  1. Martin Odersky



scala.Option[T]




scala.Some


class Some[+A](x: A) extends Option[A] with Product

Class Some[A] represents existing values of type A.

attributes: final
go to: companion
source: Option.scala
    version 
  1. 1.0, 16/07/2003

    authors: 
  1. Martin Odersky



scala.None


object None extends Option[Nothing] with Product

This case object represents non-existent values.

source: Option.scala
    version 
  1. 1.0, 16/07/2003

    authors: 
  1. Martin Odersky


scala> def commentOnPractice(input: String) = {
     | //rather than returning null
     | if (input == "test" ) Some("good" ) else None
     | }
commentOnPractice: (input: String)Option[java.lang.String]

scala> for (input <- Set("test" , "hack" )) {
     | val comment = commentOnPractice(input)
     | println("input " + input + " comment " +
     | comment.getOrElse("Found no comments" ))
     | }
input test comment good
input hack comment Found no comments


// if session.get("username") != null it will return Some. if session.get("username") == null , it will return None.

scala> Option(session.get("username")) 
res0: Option[Null] = None
res1: Option[java.lang.String] = Some(wisdomfish)

scala> res0.getOrElse("") // return ""
scala> res1.getOrElse("") // return "wisdomfish"

Comments