2016-12-14 46 views
2

在表slick documentation列與def爲什麼列表中的表格是defs而不是vals?

class Coffees(tag: Tag) extends Table[(String, Int, Double, Int, Int)](tag, "COFFEES") { 
    def name = column[String]("COF_NAME", O.PrimaryKey) 
    def supID = column[Int]("SUP_ID") 
    def price = column[Double]("PRICE") 
    def sales = column[Int]("SALES", O.Default(0)) 
    def total = column[Int]("TOTAL", O.Default(0)) 
    def * = (name, supID, price, sales, total) 
} 

確定是否有一個原因,它不應該是這樣的:

class Coffees(tag: Tag) extends Table[(String, Int, Double, Int, Int)](tag, "COFFEES") { 
    val name = column[String]("COF_NAME", O.PrimaryKey) 
    val supID = column[Int]("SUP_ID") 
    val price = column[Double]("PRICE") 
    val sales = column[Int]("SALES", O.Default(0)) 
    val total = column[Int]("TOTAL", O.Default(0)) 
    val * = (name, supID, price, sales, total) 
} 

好像列不使用任何可能改變。

回答

3

簡短回答: 初始化順序。

龍答:

讓我們收集一些事實:

1)使用val!而非defš大部分工作(如果你在你的代碼大部分def S更改爲val的IT將最的時間表現正確 - 至少這是它是如何工作的)

2)Slick代碼的大部分示例使用def s。

因此,如果發生了錯誤,它可能會發生在一些(罕見的)情況下。

一些光可以通過這部分代碼在Slick本身散出(看看評論後if(tt == null)(類`RelationalProfile):

def column[C](n: String, options: ColumnOption[C]*)(implicit tt: TypedType[C]): Rep[C] = { 
     if(tt == null) throw new NullPointerException(
     "implicit TypedType[C] for column[C] is null. "+ 
     "This may be an initialization order problem. "+ 
     "When using a MappedColumnType, you may want to change it from a val to a lazy val or def.") 
     new Rep.TypedRep[C] { 
     override def toNode = 
      Select((tableTag match { 
      case r: RefTag => r.path 
      case _ => tableNode 
      }), FieldSymbol(n)(options, tt)) :@ tt 
     override def toString = (tableTag match { 
      case r: RefTag => "(" + _tableName + " " + r.path + ")" 
      case _ => _tableName 
     }) + "." + n 
     } 
    } 

如果你看一看提交介紹了這種變化: https://github.com/slick/slick/commit/be2ff6513d46abc9a25c8752c2931a786d4c5ad6

你應該找到相當不錯的解釋(提交評論)