All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.osgl.util.Const Maven / Gradle / Ivy

The newest version!
package org.osgl.util;

/*-
 * #%L
 * Java Tool
 * %%
 * Copyright (C) 2014 - 2017 OSGL (Open Source General Library)
 * %%
 * Licensed 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.
 * #L%
 */

import org.osgl.$;
import org.osgl.Lang;

import java.io.*;

/**
 * Represent an immutable value
 * @param  the generic type of the object stored in the value
 */
public final class Const implements Serializable {

    private T v;

    /**
     * Construct a Const with a value
     * @param value the value to be stored in the `Const`
     */
    private Const(T value) {
        v = value;
    }

    /**
     * Returns the object stored in this `Val`
     * @return the object stored
     */
    public T get() {
        return v;
    }

    @Override
    public String toString() {
        return S.string(v);
    }

    public Lang.Var toVar() {
        return Lang.var(v);
    }

    public Lang.Val toVal() {
        return Lang.val(v);
    }

    @Override
    public boolean equals(Object o) {
        return (this == o || ((o instanceof Const) && Lang.eq(((Const)o).v, v)));
    }

    @Override
    public int hashCode() {
        return Lang.hc(v);
    }

    public static  Const of(E t) {
        return new Const(t);
    }

    public static  Const of(Lang.Var var) {
        return null == var ? new Const(null) : new Const(var.get());
    }

    public static void main(String[] args) throws Exception {
        Const x = $.constant("abc");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        new ObjectOutputStream(baos).writeObject(x);
        byte[] ba = baos.toByteArray();
        ByteArrayInputStream bais = new ByteArrayInputStream(ba);
        Const y = (Const)new ObjectInputStream(bais).readObject();
        System.out.println(y.get());
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy