Skip to content

Instantly share code, notes, and snippets.

@chochos
Created June 14, 2017 14:35
Show Gist options
  • Save chochos/9535e9d908cb9e122bead4e9c0db6e6b to your computer and use it in GitHub Desktop.
Save chochos/9535e9d908cb9e122bead4e9c0db6e6b to your computer and use it in GitHub Desktop.
Definition of the root types in Ceylon
//Anything can only have two subtypes: Object and Null
shared abstract class Anything() of Object | Null {}
shared class Object() extends Anything() {}
//Null can only have one instance, called null
shared abstract class Null()
of null
extends Anything() {}
shared object null extends Null() {}
//So null is not a keyword, it's a regular declaration
//This foo can take a String or null:
String|Null foo = "hey";
//There's syntax sugar for a union type with Null:
String? foo = "hey";
String|Integer? bar = 1;
//The exists operator tells you if something is NOT Null
if (exists bar) {
//Inside here, bar is of type String|Integer
}
//You can obviously check directly for a type
if (is String bar) {
//Inside here, bar is of type String
} else {
//Inside here, bar is of type Integer|Null
}
//You can use Null (or Object) in generics, for type boundaries
void baz<T>(T t)
given T satisfies Object {}
//Because of the constraint on T, you can't do this:
baz(foo);
baz(bar);
//It won't compile because the type contains Null
//so you need to narrow it
if (exists foo) {
baz(foo);
}
//Look at Iterable and Sequential/Sequence/Empty
//for a clever use of Null and Nothing in type
//parameters, allowing for a typesafe way to check
//for emptiness at compile time.
@vasily-kirichenko
Copy link

all these are exactly the same in Kotlin.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment