k47.cz
výběr kolo foto makro povídky kultura
koronavirus TECH ▞▞ 🞄⬤🞄 | twitter RSS

Java boilerplate vs. Scala

9. 12. 2010 (aktualizováno 30. 5. 2021) — k47 (CC by)

1. ukázka po­chází odsud

// Java
class Employee
{
    private final String name;
    private final int age;
    private final int salary;

    public Employee(String name, int age, int salary)
    {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    public String getName()
    {
        return this.name;
    }

    public int getAge()
    {
        return this.age;
    }

    public int getSalary()
    {
        return this.salary;
    }

    @Override
    public String toString()
    {
        return String.format("%10s(%2d) ... $%d", this.getName(), this.getAge(), this.getSalary());
    }
}
// ekvivalentní třída ve Scale
case class Employee(name: String, age: Int, salary: Int) {
  override def toString = f"$name%10s($age%2d) ... $$$salary%d"
}

2. ukázka je odtud

// Java
import java.util.*

class Item {
    int i;
    public Item(int i) {
        this.i = i;
    }
}

class Pair {
    public Item item1;
    public Item item2;

    public Pair(int i1, int i2) {
        this.item1=new Item(i1);
        this.item2=new Item(i2);
    }
}

public class Test {
    public static void main(String[] args) {
        System.console().readLine("press enter to begin");

        int n = Integer.parseInt(args[0]);
        List<Pair> list = new ArrayList<Pair>();
        for (int i=0; i<n; i++) {
            if (i%1000 == 0) {
                System.out.print(i + "\t");
            }
            list.add(new Pair(i, i));
        }

        System.console().readLine("\ndone, press enter again");
    }
}
// Scala
case class Item(i: Int)

case class Pair(item1: Item, item2: Item) {
  def this(i1: Int, i2: Int) = this(Item(i1), Item(i2))
}

object Test extends App {
  System.console.readLine("press enter to begin");

  val n = args(0).toInt
  val list = for (i <- 0 to n) yield {
    if (i % 1000 == 0) {
      print(i + "\t")
    }
    new Pair(i, i)
  }

  System.console.readLine("\ndone, press enter again")
}
píše k47 & hosté, ascii@k47.cz