PMessage.java

/*
 * Copyright 2015-2016 Providence Authors
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package net.morimekta.providence;

import net.morimekta.providence.descriptor.PField;
import net.morimekta.util.Stringable;

import javax.annotation.Nonnull;
import javax.annotation.concurrent.Immutable;

/**
 * Base class for all messages.
 */
@Immutable
public interface PMessage<Message extends PMessage<Message>>
        extends PMessageOrBuilder<Message>, Comparable<Message>, Stringable {
    /**
     * @param field The field.
     * @param <F> The message field type.
     * @return Whether the field is present.
     */
    default <F extends PField<Message>> boolean has(@Nonnull F field) {
        return has(field.getId());
    }

    /**
     * @param field The field.
     * @param <T> The return type.
     * @param <F> The message field type.
     * @return Whether the field is present.
     */
    default <T, F extends PField<Message>> T get(@Nonnull F field) {
        return get(field.getId());
    }

    /**
     * Get a builder that extends the current object.
     *
     * @return The builder instance.
     */
    @Nonnull
    PMessageBuilder<Message> mutate();

    /**
     * Shorthand for merging two messages.
     *
     * @param other The message to merge over this messages' values.
     * @return The merged message.
     */
    @Nonnull
    default Message mergeWith(Message other) {
        return mutate().merge(other).build();
    }

    /**
     * Pure string representation of content. Does not contain type info.
     *
     * @return String representation.
     */
    @Nonnull
    @Override
    String asString();
}