Skip to content

Add ! ? to access nested optional stuff by unwrapping to None or non-optional value #1859

@plajjan

Description

@plajjan

So imagine we have some types, perhaps nested, like this, and they are all using optional values, it becomes quite tedious to access the inner string field.

class A:
    b: ?B

class B:
    c: ?C

class C:
    s: ?str

def current(a: ?A):
    if a != None:
        b = a.b
        if b != None:
            c = b.c
            if c != None:
                s = c.s
                if s is not None:
                    parts = s.split(",")

def new_opt(a: ?A):
    # Using ? will shortcut and return None if any accessed field is None
    parts: ?list[str] = a?.b?.c?.s
    if parts != None:
        for part in parts:
            print("Got a part:", part)    

def new_nonopt(a: ?A):
    # Using ! will check each field and if it is None we will get an exception. If all fields are not-None then we can proceed and thus the return value is a non-optional `list[str]`
    parts: list[str] = a!.b!.c!.s
    for part in parts:
        print("Got a part:", part)

? to return optional with early shortcut if intermediate things are None

! to throw exception

Swift calls ? "optional chaining" !? and ! is "forced unwrapping"

Metadata

Metadata

Labels

CompilerRelated to the Acton compilerenhancementNew feature or request

Projects

Status

🔖 Ready

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions