Friday, February 12, 2021

Defining the sealed class and all its permitted types in a single file

Look at the below example in which the sealed interface and all the class that implements it are defined in the same source file

import java.util.Random;

public sealed interface Pet permits Cat, Dog {

    final Random random = new Random();
    
    default Pet myLuckyPet() {
        if(random.nextInt(2) == 0) {
            return new Cat();
        }
        return new Dog();
    }
}

final class Cat implements Pet {

}

final class Dog implements Pet {

}

Here Pet interface is a sealed type and permits only Cat and Dog to inherit from it. 

We define the implementing Cat and Dog classes in the same file. 

We also have a default method in Pet interface which returns a Pet instance (Cat or Dog) randomly. 

Nothing unusual about it. Restrictions of Java applies here as well, that Cat and Dog are package private and can be used only within the same package. If we want the Cat & Dog to be public, they would have to be defined in their own files.

But one advantage of defining a sealed type and its permitted types in the same file is that we can omit the permits clause in the Pet declaration. Java would infer it and include all the implementing types that are defined in the same source file as the set for permits types. 

public sealed interface Pet {

    final Random random = new Random();
    
    default Pet myLuckyPet() {
        if(random.nextInt(2) == 0) {
            return new Cat();
        }
        return new Dog();
    }
}

final class Cat implements Pet {

}

final class Dog implements Pet {

}

This code snippet behaves the same was as the 1st one. When defined in the same file, Java can infer the permitted types and we don't need to provide the permits clause with the list of allowed subtypes.

But when Permits is provided, full list of all permitted types must be specified include types defined in the same file and elsewhere.

Note however that when defining a sealed class without the permits clause, at least one subtype definition should be provided in the same file.  

Sample code used in this post can be downloaded from https://github.com/ashokkumarta/awesomely-java/tree/main/2021/02/Language-Features/Sealed-classes/Single-file

No comments:

Post a Comment