scala的优雅--自定义控制结构

C#有using 控制结构 如下:
using (TextReader textReader = new StreamReader(filename))
{
return textReader.ReadLine();
}

用scala实现如下
object Control {
def using[A <: {def close(): Unit}, B](param: A)(f: A => B): B =
try {
f(param)
} finally {
param.close()
}
import scala.collection.mutable.ListBuffer
def bmap[T](test: => Boolean)(block: => T): List[T] = {
val ret = new ListBuffer[T]
while(test) ret += block
ret.toList
}
}

用java实现找所有Person 的功能
import java.sql.*;
import java.util.ArrayList;
public class Person {
private String name;
private int age;
private boolean valid;
public Person(String n, int a, boolean v) {
name = n;
age = a;
valid = v;
}
public static ArrayList<Person> findPeople(Connection conn)
throws SQLException {
Statement st = conn.createStatement();
try {
ResultSet rs = st.executeQuery("SELECT * FROM person");
try {
ArrayList<Person> ret = new ArrayList<Person>();
while (rs.next()) {
ret.add(new Person(rs.getString("name"),
rs.getInt("age"),
rs.getBoolean("valid")));
}
return ret;
} finally {
rs.close();
}
} finally {
st.close();
}
}
}

同样的功能用刚才定义的自定义控制结构实现
case class Person(name: String, age: Int, valid: Boolean)
object Person {
import Control._
import java.sql._
def findPeople(conn: Connection): List[Person] =
using(conn.createStatement){st =>
using (st.executeQuery("SELECT * FROM person")){rs =>
bmap(rs.next){
new Person(rs.getString("name"), rs.getInt("age"), rs.getBoolean("valid"))
}
}
}
}
scala有强大的dsl能力,值得期待

你可能感兴趣的:(java,sql,scala,Ruby,groovy)