01.類型推斷(Type Inference)

Scala’s sensible static typing and type inference
自適應靜態型別
類型推斷(Type Inference)

靜態語言最大的特點是在編譯程序的階段, 就由編譯器(Compiler)明確的檢查其中的特定值的類型定義之正確, 進而能在執行程序階段(RunTime, RT)能達到相對於動態語言所不及的RT速度效能. - WisdomFish.ORG

Scala 與 Java 平台的不同,Scala 大量利用了類型推斷(type inferencing),這意味著,
  1. 編譯器主動深入分析 code 以確定特定值的類型,無需開發人員干預,可視為初級 Testing
  2. 在必要時才由開發者進行明確的類型宣告。類型推斷僅需要較少的冗餘類型 code





Type Inference



scala> import java.util._
import java.util._

// 最沒效率的寫法
scala> val x: HashMap[Int, String] = new HashMap[Int, String]( )
x: java.util.HashMap[Int,String] = {}

scala> val x: HashMap[Int, String] = new HashMap[Int, String] 
x: java.util.HashMap[Int,String] = {}

// Scala - Type Inference
scala> val x: Map[Int, String] = new HashMap
x: java.util.Map[Int,String] = {}

scala> val x = new HashMap[Int, String]    
x: java.util.HashMap[Int,String] = {}

scala> val builder = new java.lang.StringBuilder("WisdomFish")
builder: java.lang.StringBuilder = WisdomFish

scala> builder.getClass
res4: java.lang.Class[_] = class java.lang.StringBuilder

scala> val builder = new java.lang.StringBuilder      
builder: java.lang.StringBuilder = 

scala> builder.getClass                         
res5: java.lang.Class[_] = class java.lang.StringBuilder


Container


Scala 可將任意非容器類型引用賦給 Any, Any 為所有 Scala 類型的基/超類.
scala> val x = 2
x: Int = 2

scala> var fish1 = 2
fish1: Int = 2

scala> var fish2: Any
<console>:14: error: only classes can have declared but undefined members
(Note that variables need to be initialized to be defined)
       var fish2: Any
           ^

scala> var fish2: Any = null
fish2: Any = null

scala> fish2 = fish1
fish2: Any = 2



Scala 預設情況下, 要求 = 號二邊的容器內容必須相同, 除非以規則:協變(Covariance) 來允許例外情況
scala> var a2 = new java.util.ArrayList[Any]   
a2: java.util.ArrayList[Any] = []

scala> var a1 = new java.util.ArrayList[String]
a1: java.util.ArrayList[String] = []

scala> a1 = a2
<console>:16: error: type mismatch;
 found   : java.util.ArrayList[Any]
 required: java.util.ArrayList[String]
       a1 = a2
            ^

scala> a2 = a1
<console>:16: error: type mismatch;
 found   : java.util.ArrayList[String]
 required: java.util.ArrayList[Any]
       a2 = a1
            ^



Nothing / Any


Nothing 是Scala 所有 class 的最底層子類別, 只要是無參數化的容器都是 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


無法將上層類型容器指向給最下層 Nothing 類型容器
scala> val a1 = new java.util.ArrayList[String]
a1: java.util.ArrayList[String] = []

scala> var a2 = new java.util.ArrayList        
a2: java.util.ArrayList[Nothing] = []

scala> a2 = a1                                 
<console>:16: error: type mismatch;
 found   : java.util.ArrayList[String]
 required: java.util.ArrayList[Nothing]
       a2 = a1
            ^



Comments