Skip to content

Using bijection from java

johnynek edited this page Jan 12, 2013 · 3 revisions

Implementing a Bijection

Here's an example of implementing a bijection in Java:

    import com.twitter.bijection.AbstractBijection;

    // This is not a mathematically correct bijection for all strings,
    // since only the subset of canonical representations of Long as valid inputs.
    // It is here only as a convenient example implementation
    public class StringToLong extends AbstractBijection<String,Long> {
        @Override
        public Long apply(String a) {
            return Long.parseLong(a);
        }

        @Override
        public String invert(Long b) {
            return b.toString();
        }
    }

Accessing default Bijections from Java:

To access default bijections, find them in the scala object Bijection, which is compiled to java bytecode as:

import com.twitter.bijection.Bijection$;

Bijection<byte[],Base64String> bytes2Base64 = Bijection$.MODULE$.bytes2Base64();

The details of how scala compiles to JVM bytecode are beyond the scope of this document, but the rule is: to access vals/methods of a scala object A then call the method you want on A$.MODULE$.

(Scala <=> Java) Collection Bijections:

See: Collection Bijections for bijections between Iterator/List/Map and more in their Java and Scala versions. This might make Java interop with scala easier.