ceylon / ceylon.language

DEPRECATED
Apache License 2.0
153 stars 57 forks source link

Unable to compare union type (Float? | Integer?) #796

Closed steowens closed 8 years ago

steowens commented 8 years ago

So far I can find no way to build a compare function which accepts a class which has a value of type (Float? | Integer?).

For example:

shared default actual Comparison compare(Number other){
        if(!(other.val exists)&&!(val exists)){
            return equal;
        } else if(val exists && !(other.val exists)){
            return larger;
        } else if(!(val exists) && other.val exists){
            return smaller;
        } else {
           if(val is Float){
               if(other.val is Float){
                  // Generates compiler error
                  // Specified expression must be assignable to declared type of ov:
                  //        Integer?|Float? (Null|Integer|Float) is not assignable to Float
                   Float ov = other.val;

                  // Generates compiler error
                  // Incorrect syntax: missing statement-ending ; at other expecting statement-ending ;
                  Float ov2 = (Float) other.val;

                   // Generates compiler error
                  // Operand expressions must be comparable: 
                  //   Integer?|Float? (Null|Integer|Float) is not a subtype of Comparable 
                  return val <=> other.val;
               }
           }

        }

    }

Even though the above code tests the type of val and other.val and asserts them to be the same, it is impossible ot cast or compare the two values.

thradec commented 8 years ago

Did you try type narrowing? In your example ...

if( is Float f = val, is Float f2 = other.val ) {
    return f <=> f2;
}
gavinking commented 8 years ago

Hi, @steowens, the syntax other.val is Float does not perform type narrowing, it is just a plain expression of type Boolean. What you would need is an is condition, as shown above by @thradec.

Also the syntax (Float) other.val is simply not legal Ceylon. That is a Java/C typecast, which does not exist in Ceylon.

You can find more information about this syntax here, here, and here.

I'm closing this issue since it's not a bug in Ceylon.

steowens commented 8 years ago

Thank you. Just saw your question and response. I am unfamiliar with Ceylon and was evaluating the language. Had the issue type been available I would have selected (question) as the issue type. Do you have a publicly accessible forum which we could use to ask such questions?

DiegoCoronel commented 8 years ago

@steowens you can try both:

I believe those are enough to start.. but theres also dev chat and forum

steowens commented 8 years ago

Thank you. I didn't see those mentioned in your README.md file, nor on your Wiki. It might be a nice bit of info to include in your github site. I am sure I am not the only person who will be interested in learning where to go to ask questions.