簡體   English   中英

如果 Scala 方法可以拋出/返回錯誤但具有 Unit 返回類型,那么它應該具有什么返回類型?

[英]What return type should a Scala method have if it can throw/return errors but has Unit return type?

所以通常當我們運行一個既可以失敗又可以返回值的方法時,我們可以將我們的方法返回類型編碼為Either[SomeErrorType, ReturnType] 但是很多時候我們為了它的副作用運行一個方法,所以返回類型是Unit

我當然可以返回一個Either[SomeErrorType, Unit]但這絕對看起來很奇怪。

我也可以只返回一個Option[SomeErrorType]但它看起來並沒有好多少(並且打破了與其他Either[SomeErrorType, NonUnitReturnType]一個可能存在的對稱性Either[SomeErrorType, NonUnitReturnType] s。

在這些情況下你的方法是什么?

  1. def m(): Unit // and implicitly know that exceptions can be thrown? ;
  2. def m(): Either[SomeErrorType, Unit] // this is odd
  3. def m(): Option[SomeErrorType] // this is odd, as it makes it look as the return type of on a successful run is an error code. m() def m(): Option[SomeErrorType] // this is odd, as it makes it look as the return type of on a successful run is an error code.
  4. 其他我想不到的?

謝謝

在這種情況下,我使用Try[Unit]

它編碼該方法的結果要么成功要么失敗,並帶有一些Exception ,可以進一步處理。

  • vs T => Unit Try將錯誤提升到應用程序級別,在簽名中編碼可能會出現一些錯誤並允許應用程序將其作為值處理。
  • vs. Option[T] => Option 只能編碼操作是否有值
  • vs. Either[SomeErrorType, Unit] => Try使用 monadic 結構更容易工作。

我用過這樣的東西來實現檢查。 (假想的例子)

for {
    entity <- receiveEntity // Try[Entity]
    _ <- isRelational(entity)
    _ <- isComplete(entity)
    _ <- isStable(entity)
} yield entity

其中每個檢查的形式為: Entity => Try[Unit]

如果所有檢查都通過了檢查失敗的第一個錯誤,這將返回entity

另一種尚未提及的選項是從Validated 到目前為止提到的所有選項( TryEitherOption )都是 monad,而Validated是一個應用函子。 實際上,這意味着您可以從多個返回Validated方法中累積錯誤,並且您可以並行執行多個驗證。 這可能與您無關,這與原始問題有點正交,但我仍然覺得在這種情況下值得一提。

至於最初的問題,將Unit返回類型用於副作用函數是完全沒問題的。 當您定義“真實”(正確、成功等)返回類型時,此函數也可以返回錯誤這一事實不應妨礙您。 因此,如果我要從您的原始選項中進行選擇,我會選擇Either[Error, Unit] 它對我來說絕對不奇怪,如果有人看到它的任何缺點,我想知道它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM