我最近改變了很多我的Scala代碼,以避免使用null
實例化變量,而是使用Option
。例如,我以前有:使用Scala選項
var cxn: RepositoryConnection = null
cxn = repo.getConnection()
//do something with the connection, then close it
cxn.close()
現在,我的代碼看起來更像這樣。
var cxn = None : Option[RepositoryConnection]
cxn = Some(repo.getConnection())
//do something with the connection, then close it
現在我遇到的問題是當我想調用一個與RepositoryConnection類型關聯的方法。我嘗試:
cxn.close()
,看到這個錯誤:
value close is not a member of Option[org.openrdf.repository.RepositoryConnection]
現在,我用null
時,這個操作工作就好了,因爲cxn
是RepositoryConnection
對象,而不是一個Option[RepositoryConnection]
。有沒有簡單的方法來調用close()
方法,現在我正在使用Option
?
你爲什麼不能用'VAL CXN嘗試= repo.getConnection()'在這種情況下?這裏真正的問題是使用var並將其設置爲null/None,然後在其中輸入實際值。使用'Option'並不能改善這一點。 – puhlen
原因是,由於我的代碼的設計,cxn需要是一個全局變量,並且在稍後纔會設置。事實上,當cxn初始化時,repo對象還沒有創建,並且由於我正在使用的技術,我相信這是必需的。 – hayfreed
你不想要選項,你需要一個懶惰的val你的描述的問題。 – pedrofurla