I'm new to Scala and trying to write some programs to get better at it. I wrote a flow (version 1) that is very Java-like and I'm trying to write it using higher order functions (version 2).
version 1:
val entry: Option[Int] = getEntry()
if (entry.isDefined) {
val cachedEntry = entry.get
if (cachedEntry.state.isActive) {
return cachedEntry
} else {
Cache.invalidateCachedEntry(cachedEntry)
}
}
Cache.createNewEntry()
version 2:
val entry: Option[Int] = getEntry()
entry.filter(_.state.isActive).orElse((() => {
Cache.invalidateCachedEntry _
Option(Cache.createNewEntry())
})()).get
I'm not sure if this is the correct approach or there is a better way of doing this?
entryis optionalInt, but later you cal.state.isActive.entryisNonethen V1 does not callCache.invalidateCachedEntry()but in V2 it does.cachedEntry.state.isActive. I've updated the question. 2) I need to return an integer value (returned bycreateNewEntry(), not an optional value)invalidateCachedEntrysimply removes thecachedEntryfrom the map so it should be fine either way (should be just a no-op).