Search code examples
scalaapache-kafkasyntaxutility

Scala Optional best practices


def canAppendOffset(offset: Long): Boolean = {
  toRelative(offset).isDefined
}

private def toRelative(offset: Long): Option[Int] = {
  val relativeOffset = offset - baseOffset
  if (relativeOffset < 0 || relativeOffset > Int.MaxValue) None
  else Some(relativeOffset.toInt)
}

I get confused when running into the aforementioned code. The code if from Kafka LogSegment. I am wondering why we need a Optional here rather than simply return a boolean in canAppendOffset(). It looks unnecessary to me why we need to create an Optional and access an field which records the boolean value I need. I think there must be some logic in software design aspects. Could anyone give any suggestions on where and why to use Optional in Scala?


Solution

  • There appears to be a couple of misconceptions here.

    ...create an Optional and access a field which records the boolean value...

    There is no field here. isDefined is a method in the Option class that tests whether this instance is Some() or None.

    ...why we need an Optional here rather than simply return a boolean in canAppendOffset().

    But canAppendOffset() does "simply return a Boolean". It's toRelative() that "creates" the Option and it does that because, while it is supposed to return a "relative" from the given offset, it might actually fail to do so if a valid result is impossible.

    So it returns an Option[Int], thus telling the caller, "Here's Some(relative) if it can be calculated from the given offset, but it's None if I can't calculate a good result for you."