Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Scala Function & Tuple generator for java
#!/usr/bin/env python3
A script to generate the barebone implementation of scala’s
Function# and Tuple# types for use in java.
I made this to allow Java projects to specify function signatures
which play nice with scala, without depending on scala’s stdlib.
from os.path import basename
#Maximum number of Tuple and Product items, as well as function arguments
INTRO = '''/** This class is generated automatically.
* Run {} to regenerate it. */
package scala;
FUNC_TEMPLATE = INTRO + '''public abstract class Function{i}<{typeparamsR}> {{
public abstract R apply({args});{tupled}
public R tupled(Tuple{i}<{typeparams}> t) {{
return apply({telems});
TUPLE_TEMPLATE = INTRO + '''public class Tuple{i}<{typeparams}> {{
public Tuple{i}({args}) {{
public boolean equals(Tuple{i}<{objects}> t) {{
return {equal};
public String toString() {{
return "(" + {stradd} + ")";
def jsep(fmt, i, sep=', ', extra=None):
'''Returns a joined list of `format` with increasing numbers until i'''
elems = [fmt.format(j) for j in range(1, i+1)]
if extra is not None:
return sep.join(elems)
def create_function(i, fdict):
'''Creates Function<i>.java'''
fdict['typeparamsR'] = jsep('T{}', i, extra='R')
fdict['tupled'] = ''
if i != 0:
fdict['telems'] = jsep('t._{}', i)
fdict['tupled'] = METHOD_TUPLED_TEPLATE.format_map(fdict)
with open('Function{}.java'.format(i), 'w') as function_file:
def create_tuple(i, fdict):
'''Creates Tuple<i>.java'''
fdict['fields'] = jsep('public T{0} _{0};', i, sep='\n\t')
fdict['assigns'] = jsep('this._{0} = t{0};', i, sep='\n\t\t')
fdict['equal'] = jsep('_{0}.equals(t._{0})', i, sep='\n\t\t\t&& ')
fdict['stradd'] = jsep('_{}', i, sep=' + ", " +')
fdict['objects'] = jsep('Object', i)
with open('Tuple{}.java'.format(i), 'w') as tuple_file:
def main():
'''Creates all functions and tuples scala provides'''
fdict = {'i': 0, 'args': ''}
create_function(0, fdict)
for i in range(1, MAX_ARGS+1):
fdict['i'] = i
fdict['typeparams'] = jsep('T{}', i)
fdict['args'] = jsep('T{0} t{0}', i)
create_tuple(i, fdict)
create_function(i, fdict)
if __name__ == '__main__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment