- String name=null;
- if( xxx ) name="yyy";
- else name="zzz";
can be replaced by
- val name = if( xxx ) "yyy"; else "zzz";
The benefit (other than less boiler plate code) is that name can now be a val instead of a var.
Another other point about returns: The return keyword is not required when returning a value from methods or control structures. The last value is always the return value. This is why you will get an error if the last line in a method or control structure is an assignment.
Examples:
- scala> val name = if( 1==2 ) "Jesse" else "Mauricio"
- name: java.lang.String = Mauricio
- scala> println(name)
- Mauricio
- scala> val collection = for( i <- 1 to 100; if(i%20 == 3) ) yield i
- collection: Seq.Projection[Int] = RangeFM(3, 23, 43, 63, 83)
- scala> collection.foreach( i => print( i +" ") )
- 3 23 43 63 83
- scala> val someObj:AnyRef = "Hello"
- someObj: AnyRef = Hello
- scala> val choice = someObj match {
- | case _:java.io.File => "File"
- | case _:String => "String"
- | case _ => "Dunno"
- | }
- choice: java.lang.String = String
- scala> val result = try {
- | "two".toInt
- | }catch{
- | case e:NumberFormatException => -1
- | case _ => 0
- | }
- result: Int = -1
- scala> var i=0
- i: Int = 0
- // while and do-while do not have return values
- scala> while( i<4 ){
- | "22"
- | i += 2
- | }
- scala> println( if(i>0) "great" else "less" )
- great
- // code blocks return the last statement
- scala> val m = {
- | val x = 1
- | x + 2
- | }
- m: Int = 3
Hi Jesse,
ReplyDeletethanks for posting this wonderful notes on scala.
I got stuck on this stuff
collection.foreach( i => print( i +" ") )
Tried to use "_" in the above call
collection.foreach(print( _ +" "))
but getting an error. Trying to understand why this happens. Any insight would be appreciated
Thanks in advance
I do not know the details but essentially what is happening is that there are 2 functions being created:
ReplyDelete_ + " "
and
print _
In the function: collection.foreach(print( _ +" "))
The _ refers to the top level function but from a compiler point of view it is not so clear what the _ is standing in for.
From what I understand the error is one of technical restrictions based on how complicated it is to make the compiler and type inferencer figure out what types are required and so on.
As a rule of thumb that I go by is that the _ placeholder should only be used where there is no ambiguity of what it applies to.
So in order to pass the value "down" to the inner function you need to assign the value to an explicit value.
Hope that makes some sense :P
Jesse, thanks for the clarification, something similar explained over here too.. http://bit.ly/8Hcgh2
ReplyDelete