GFX::Monk Home

Posts tagged: scala

Scala Investigation: First-Class Functions

I’ve just spent some time learning about the difference between scala’s functions and methods. It’s a surprisingly complicated topic, so I’ll defer to the smart folks on stack overflow for the explanation itself:

Difference between method and function in Scala

Here are some interesting points / examples I took from that topic:

Scala trick: convert java.lang.Object to Option[A]

So let’s say you have a java method:

public Object getSomething(String key) { ... }

This returns an Object, or null. Ideally it would have a generic type so that it at least returned the type you expect (like String), rather than Object, but that’s java for you. What’s a scala chap to do with such an ugly method?

val obj = getSomething("key")
val maybeObj = obj match {
	case s:String => Some(s)
	case _ => None
}
val actualObj = maybeObj.getOrElse("")

Not very nice, is it? We should abstract this (unfortunately) common pattern!

What The Scala?

Here’s a puzzler for scala fans: What will be the console output of the following program:

def foo1() {
	println("> foo1()")
	return "foo1"
}

def foo2() {
	println("> foo2()")
	"foo2"
}

def foo3() = {
	println("> foo3()")
	"foo3"
}

def foo4():String {
	println("> foo4()")
	"foo4"
}

println(foo1())
println("---------------")
println(foo2())
println("---------------")
println(foo3())
println("---------------")
println(foo4())

Look carefully at each of the def lines, and write down what you think the output will be.