Search code examples
ponylang

How to assign the return value of a method that can raise an error?


In pony if there is a method on a class that can raise an error we use the ? operator to call the method in a try...end block. For example:

let my_third_list = List[String].from(["First"; "Second"; "Third"])
try env.out.print(list.apply(1)?) end // Second

But what if I want to assign the return value of apply method to a name like item and then print item

let my_third_list = List[String].from(["First"; "Second"; "Third"])
try let item = list.apply(1)? end // Second
env.out.print(item)

compiler says can't find declaration of 'item'

How do I do that? and what is the best way of doing things in these cases?


Solution

  • All "statements" are expressions in Pony, so you can put an assignment outside the try block, such

    let item = try list.apply(1)? else "<notfound>" end
    env.out.print(item)
    

    The else will be required, since a rvalue must be available.