Sunday, September 4, 2011

Right question in scala world

When I started some real small project using scala. I read some rows of data from database and as usual wanted to
save it in some list. So first question appears in my mind
How to add some element to list ?
def testPersons(): List[Person] = {
    val conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl")
    var persons = new List[Person]()
    try {
     val statement = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)
     val rs = statement.executeQuery("SELECT * FROM Person where user_name like '%test%'")
     while (rs.next) {
       personsBuf.add(new Person(rs.getString("user_name"), rs.getString("first_name"), rs.getString("last_name")))
     }
    } finally {
     conn.close
    }
    persons
 }
 but after some investigation I realized the question is completely wrong.
 Philosophy of scala differ from philosophy of java. and first of all you must think immutably.
 You create list in variety of ways
 val fruit = List("apples", "oranges", "pears")
val nums = List(1, 2, 3, 4)
val diag3 = List(List(1, 0, 0), List(0, 1, 0), List(0, 0, 1))
val empty = List()
val fruit = "apples" :: ("oranges" :: ("pears" :: Nil))
val nums = 1 :: (2 :: (3 :: (4 :: Nil)))
val diag3 = (1 :: (0 :: (0 :: Nil))) ::
(0 :: (1 :: (0 :: Nil))) ::
(0 :: (0 :: (1 :: Nil))) :: Nil
val empty = Nil
but you after creating you can not change it because it is immutable. You can only create new one. It is like string in java.
the right way of my function is :
def testPersons(): List[Person2] = {
    val conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl")
    var personsBuf = new scala.collection.mutable.ListBuffer[Person2]()
    try {
     val statement = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)
     val rs = statement.executeQuery("SELECT * FROM Person where user_name like '%test%'")
     while (rs.next) {
       personsBuf += new Person2(rs.getString("user_name"), rs.getString("first_name"), rs.getString("last_name"))
     }
    } finally {
     conn.close
    }
    personsBuf.toList
 }
I really need to use ListBuffer like mutable list inside function and than return immutable list to outside world.
And you can relay to this list on any place of you program, no one can change it or corrupt it. It is immutable.
It is scala world.