If you're okay with a mutable variable (and seems like you are as you used var foos
in both examples and only specified an immutable collection) this should match your needs:
var foos = Map.empty[Int, Foo]
def fooOf(n: Int): Foo = {
foos.getOrElse(n, {
foos = foos.updated(n, new Foo(n))
foos(n)
})
}