Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I replace a java mutable class with its immutable couterpart in scala?
    text
    copied!<p>I'm trying to understand how to use immutable classes in scala as a replacement for mutable java classes.</p> <p>My example use case is searching for contacts in a database. When programming imperatively you would pull each field from the database table and set it on the java object.</p> <p>How would you do this in Scala using immutable types and functional style?</p> <p>I know I could use a constructor and create a new instance of the object passing all required data to it, but for large complex data structures this doesn't seem elegant. </p> <p>What is the "Scala" / "Functional" way to accomplish this? Or what are some best practices related to constructing complex immutable types?</p> <pre><code>public List&lt;Contact&gt; search(String firstName, String lastName) throws SQLException { List&lt;Contact&gt; contacts = new ArrayList&lt;Contact&gt;(); Connection con = null; PreparedStatement ps = null; ResultSet rs = null; try { con = dataSource.getConnection(); ps = con.prepareStatement("select * from contacts where first_name like ? and last_name like ?"); ps.setString(1, "%" + firstName + "%"); ps.setString(1, "%" + lastName + "%"); rs = ps.executeQuery(); while (rs.next()) { Contact contact = new Contact(); contact.setFirstName(rs.getString("first_name")); contact.setMiddleName(rs.getString("middle_name")); contact.setLastName(rs.getString("last_name")); Date birthday = rs.getDate("birthday"); if (birthday != null) { contact.setBirthday(new Date(birthday.getTime())); } contacts.add(contact); } } catch (Exception e) { e.printStackTrace(); } finally { rs.close(); ps.close(); con.close(); } return contacts; } </code></pre> <p>Contact POJO</p> <pre><code>import java.util.Date; public class Contact { private String firstName; private String middleName; private String lastName; private Date birthday; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getMiddleName() { return middleName; } public void setMiddleName(String middleName) { this.middleName = middleName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload