0

以下代码无法编译,因为编译器认为“with”表达式的类型是 (U8 | None) 尽管我不知道它的主体会如何变为 None

class Disposable
  new create() => None
  fun dispose() => None
  fun value(): U8 => 42

primitive TestWith
  fun apply(): U8  =>
    with d = Disposable do 
      d.value()
    end

但是,如果我将“else”部分添加到“with”中-类型的一切都会好起来的。但是编译器抱怨“尝试表达式永远不会导致错误”

primitive TestWith
  fun apply(): U8  =>
    with d = Disposable do 
      d.value()
    else
      0
    end 

有任何想法吗?

4

1 回答 1

0

with即使嵌套代码报告错误,块也确保对象被释放。在你的情况下,身体d.value()不会产生错误。在这种情况下,您不需要with声明。

您有两个选项可以编译您的代码:

a)dispose()直接调用(看起来一点也不优雅):

class Disposable
  new create() => None
  fun dispose() => None
  fun value(): U8 => 42

primitive TestWith
  fun apply(): U8  =>
    let d = Disposable
    let result = d.value()
    d.dispose() // dispose manually
    result

b)在体内具有部分功能with

class Disposable
  new create() => None
  fun dispose() => None
  fun value(): U8? => error // partial function

primitive TestWith
  fun apply(): U8  =>
    with d = Disposable do 
      d.value() // possible failure here
    end
于 2017-02-08T14:00:44.983 回答