This link has been bookmarked by 12 people . It was first bookmarked on 17 May 2007, by Ken Wei.
-
22 Jul 10
-
If you come from an imperative (Java, Ruby) background, you'll probably recognize the following code:
x = someOperation
if !x.nil?
y = someOtherOperation
if !y.nil?
doSomething(x,y)
return "it worked"
end
end
return "it failed" -
In Java, null is a non-object. It has no methods. It is the exception to the statically typed rule (null has no class, but any reference of any class can be set to null.) Invoking a method on null has one and only one result: an exception is thrown. null is often returned from methods as a flag indicating that the method ran successfully, but yielded no meaningful value. For example, CardHolder.findByCreditCardNumber("2222222222")
-
Scala does something different.
There's an abstract class, called Option. Options are strongly typed. They are declared Option[T]. This means an Option can be of any type, but once its type is defined, it does not change. There are two subclasses of Option: Some and None. None is a singleton (like nil). Some is a container around the actual answer.
-
So, you might have a method that looks like:
def findUser(name: String): Option[User] = {
val query = buildQuery(name)
val resultSet = performQuery(query)
val retVal = if (resultSet.next) Some(createUser(resultSet))
else None
resultSet.close
retVal
}Some, you've got a findUser method that returns either Some(User) or None. So far, it doesn't look a lot different than our example above. So, to confuse everyone, I'm going to talk about collections for a minute.
-
rich list operations. Rather than creating a counter and pulling list (array) elements out one by one, you write a little function and pass that function to the list. The list calls the function with each element and returns a new list with the values returned from each call. It's easier to see it in code:
scala> List(1,2,3).map(x => x * 2)
line0: scala.List[scala.Int] = List(2,4,6) -
Option implements map, flatMap, and filter (the methods necessary for the Scala compiler to use in the 'for' comprehension.
-
when I first encountered the phrase "'for' comprehension", I got scared. I've been doing programming for years and never heard of a "comprenhension" let alone a 'for' one. Turns out, that there's nothing fancy going on, but "'for' comprehension" is just a term of art for the above construct.
-
-
21 Jun 10
-
31 May 10
-
01 Mar 10
-
16 Sep 09
-
28 Jun 09
-
09 Jan 09
-
22 Nov 07
-
17 May 07
Would you like to comment?
Join Diigo for a free account, or sign in if you are already a member.