Created
April 4, 2012 07:52
-
-
Save fupfin/2299564 to your computer and use it in GitHub Desktop.
Scala's tuple implmentation for Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package fupfin; | |
public class Tuples { | |
private Tuples() {} | |
public static <T1, T2> Tuple2<T1, T2> tuple(T1 v1, T2 v2) { | |
return new Tuple2<T1, T2>(v1, v2); | |
} | |
public static <T1, T2, T3> Tuple3<T1, T2, T3> tuple(T1 v1, T2 v2, T3 v3) { | |
return new Tuple3<T1, T2, T3>(v1, v2, v3); | |
} | |
public static <T1, T2, T3, T4> Tuple4<T1, T2, T3, T4> tuple(T1 v1, T2 v2, T3 v3, T4 v4) { | |
return new Tuple4<T1, T2, T3, T4>(v1, v2, v3, v4); | |
} | |
public static class Tuple2<T1, T2> { | |
public final T1 v1; | |
public final T2 v2; | |
private Tuple2(T1 v1, T2 v2) { | |
this.v1 = v1; | |
this.v2 = v2; | |
} | |
} | |
public static class Tuple3<T1, T2, T3> extends Tuple2<T1, T2> { | |
public final T3 v3; | |
private Tuple3(T1 v1, T2 v2, T3 v3) { | |
super(v1, v2); | |
this.v3 = v3; | |
} | |
} | |
public static class Tuple4<T1, T2, T3, T4> extends Tuple3<T1, T2, T3> { | |
public final T4 v4; | |
private Tuple4(T1 v1, T2 v2, T3 v3, T4 v4) { | |
super(v1, v2, v3); | |
this.v4 = v4; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package fupfin; | |
import static org.junit.Assert.*; | |
import static fupfin.Tuples.*; | |
import org.junit.Test; | |
public class TuplesTest { | |
@Test | |
public void testTuple2() { | |
Tuple2<String, Integer> result = tuple("a", 1); | |
assertEquals("a", result.v1); | |
assertEquals(new Integer(1), result.v2); | |
} | |
@Test | |
public void testTuple3() { | |
Tuple3<String, Integer, Boolean> result = tuple("a", 1, true); | |
assertEquals("a", result.v1); | |
assertEquals(new Integer(1), result.v2); | |
assertTrue(result.v3); | |
} | |
@Test | |
public void testTuple4() { | |
Tuple4<String, Integer, Boolean, Float> result = tuple("a", 1, true, 0.5f); | |
assertEquals("a", result.v1); | |
assertEquals(new Integer(1), result.v2); | |
assertTrue(result.v3); | |
assertEquals(0.5, result.v4, 0.001); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment