FAQ - Help and questions

How do I port Java code to Rust? What maps to what?

#porting#java#basicspublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Java classes become structs with impl blocks, interfaces become traits, checked exceptions become Result, null and Optional become Option, streams become iterators, and packages and Maven become modules and Cargo. Garbage collection is replaced by ownership. Port the data types first, then the behaviour.

Checked with rustc 1.93.0, OpenJDK 17.0.18, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

Java and Rust agree on much of the vocabulary (interfaces and traits, generics, lambdas and closures, pattern-like instanceof), and they differ on the memory model. Java has a garbage collector, references everywhere and null; Rust has owned values, explicit borrows and no null. Most of a port is therefore a change of how data is owned and passed, while the control flow carries over.

JavaRust
class with fields and methodsstruct plus an impl block
interfacetrait; use Box<dyn Trait> where a variable has an interface type
extendscomposition, trait default methods, or an enum (see the thread on classes and inheritance)
null, Optional<T>Option<T>
checked exception, throwsResult<T, E> (see the thread on Java exceptions)
List<T>, ArrayListVec<T>
Map<K, V>, HashMapHashMap<K, V>, or BTreeMap<K, V> for sorted keys
String, StringBuilder&str and String
stream().filter().map().sum()iter().filter().map().sum()
lambda (a -> a * 2)a closure (arguments between vertical bars, as in the iterator example below)
enum with fields and methodsenum with data, and an impl block
recordstruct with #[derive(Debug, Clone, PartialEq)]
synchronized, ReentrantLockMutex<T>
package, importmod, use
Maven or Gradle dependencya line in Cargo.toml
JUnit test#[test] function, run by cargo test

The Java program below has an interface implemented by a lambda, a lookup that throws a checked exception, a stream and an Optional. It was compiled and run with OpenJDK 17.0.18:

java
import java.util.*;

public class Javamap {
    interface Greeter { String greet(String name); }
    static class NotFound extends Exception { NotFound(String n) { super(n); } }

    static int findAge(Map<String, Integer> ages, String name) throws NotFound {
        Integer a = ages.get(name);
        if (a == null) throw new NotFound(name);
        return a;
    }

    public static void main(String[] args) throws Exception {
        Greeter g = n -> "Good day, " + n + ".";
        System.out.println(g.greet("Ada"));
        Map<String, Integer> ages = new HashMap<>();
        ages.put("Ada", 36); ages.put("Bo", 20);
        System.out.println(findAge(ages, "Ada"));
        try { findAge(ages, "Cy"); } catch (NotFound e) { System.out.println("not found: " + e.getMessage()); }
        System.out.println(ages.values().stream().filter(a -> a > 21).mapToInt(a -> a).sum());
        System.out.println(Optional.ofNullable(ages.get("Cy")).map(String::valueOf).orElse("unknown"));
    }
}
text
Good day, Ada.
36
not found: Cy
36
unknown

The same program in Rust, compiled and run with rustc 1.93.0:

src/main.rsrust
use std::collections::HashMap;

trait Greeter {
    fn greet(&self, name: &str) -> String;
}

struct Polite;
impl Greeter for Polite {
    fn greet(&self, name: &str) -> String {
        format!("Good day, {name}.")
    }
}

#[derive(Debug)]
enum LookupError {
    NotFound(String),
}

fn find_age(ages: &HashMap<String, u32>, name: &str) -> Result<u32, LookupError> {
    ages.get(name).copied().ok_or_else(|| LookupError::NotFound(name.to_string()))
}

fn main() {
    let g: Box<dyn Greeter> = Box::new(Polite);
    println!("{}", g.greet("Ada"));

    let ages: HashMap<String, u32> = [("Ada".to_string(), 36), ("Bo".to_string(), 20)].into_iter().collect();
    println!("{:?}", find_age(&ages, "Ada"));
    println!("{:?}", find_age(&ages, "Cy"));

    // Java: ages.values().stream().filter(a -> a > 21).mapToInt(a -> a).sum()
    println!("{}", ages.values().filter(|&&a| a > 21).sum::<u32>());
    // Java Optional<String>.map(...).orElse(...)
    println!("{}", ages.get("Cy").map(|a| a.to_string()).unwrap_or_else(|| "unknown".to_string()));
}
text
Good day, Ada.
Ok(36)
Err(NotFound("Cy"))
36
unknown

What changed besides the syntax: the lookup's possible failure is in its return type; the lambda that implemented Greeter became a named type (a closure can also implement a trait through a Fn bound); and no Integer boxing exists, since u32 is a plain value.

How to do it#

  1. Port the data classes first: fields become struct fields; decide for each whether the struct owns the data (String, Vec<T>) or borrows it (&str, &[T], which needs a lifetime). Owning is the easy start.
  2. Port the interfaces to traits and the implementing classes to structs with impl Trait for Struct.
  3. Port the methods. this becomes &self (read), &mut self (change) or self (consume).
  4. Replace exceptions with Result and null with Option, starting from the leaf methods.
  5. Replace shared mutable state (static fields, singletons, listeners) as the threads on globals and callbacks describe.
  6. Port tests last, or better first (see the thread on golden files).

Common mistakes#

  • Using Rc<RefCell<T>> for every object reference to copy Java's "everything is a reference". Start with owned values and borrows, and add sharing only where the design needs it.
  • Porting inheritance trees literally. Look at what the hierarchy was used for.
  • Expecting HashMap iteration order to match Java's. Neither promises an order; sort or use BTreeMap when order matters (see the thread on key order).

What happens to Java's equals and hashCode?#

Derive PartialEq, Eq and Hash with #[derive(...)]. The derived versions compare all fields.

How do I call my existing Java library from Rust, or the other way?#

Through JNI or the Java foreign function API, using the C-compatible layer. This thread did not run that path.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet