Question

I was hoping the following would work:

void takeOnlyStrings(String* s) {
   print(s);
}

{String|Integer*} ab = {"Hi", 1};

takeOnlyStrings(for (item in ab) if (item is String) item);

Or even this:

Boolean isString(Object o) => (o is String);
takeOnlyStrings(ab.filter(isString));

But no luck.

Was it helpful?

Solution

The syntax for narrowing the type of a value is prefix is Type val, for example:

void takeOnlyStrings(String* s) {
    print(s);
}

{String|Integer*} ab = {"Hi", 1};

takeOnlyStrings(for (item in ab) if (is String item) item);

The syntax item is String is just an operator expression that produces a Boolean value. It doesn't narrow the type of its argument.

OTHER TIPS

Here's a second possibility: in Ceylon 1.2, the new method Iterable.narrow() can be used:

void takeOnlyStrings(String* s) {
    print(s);
}

{String|Integer*} ab = {"Hi", 1};

takeOnlyStrings(*ab.narrow<String>());

Hope that helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top