If you're interested in functional programming, you might also want to checkout my second blog which i'm actively working on!!

Tuesday, March 4, 2014

Ceylon: Optional types

/**
In case you haven't heard of optional types you might
want to take your profession more seriously :)
Yes, i'm referring to constructs like Scala's algebraic type called Option
which is either a Some(T value) or a None
Ceylon does not use a wrapper class but instead makes use of 2 new cool
features which are baked into the language "Union and Intersection Types"
together with type narrowing.
So if you want to express that a value can be either of the declared type or
null, you use the syntactic sugar notation (appending a question mark)
In order to be able to call methods on an union type, you first have to narrow it down
to a specific type. In this case we do this by testing for existence.
**/
class Person(fName, middleName, lName) {
shared String fName;
shared String? middleName; //optional
shared String lName;
shared actual String string {
//below we narrow the type to String
if (exists middleName) {
return "(Person(``fName`` ``middleName`` ``lName``))";
}
return "(Person(``fName`` ``lName``))";
}
}
/**
We can however use the else construct to provide a default value if the optional type
is indeed null. This saves a few lines of code and might be even clearer.
**/
class Person2(fName, middleName, lName) {
shared String fName;
shared String? middleName; //optional
shared String lName;
shared actual String string => "(Person(``fName`` ``middleName else ""`` ``lName``))";
}
/**
This demo prints
5
<null>
**/
void optional_demo() {
//Below we use syntactic sugar notation for optional type which basically is
//the union of types Integer and Null
Integer? optional1 = getNumber("robby");
//Below we use the fully qualified union type
Integer | Null optional2 = getNumber("john");
print(optional1);
print(optional2);
}
Integer? getNumber(String name) {
return name.startsWith("r") then 5; //else null is implicit
}

No comments:

Post a Comment