Skip to content
This repository was archived by the owner on Nov 29, 2020. It is now read-only.
This repository was archived by the owner on Nov 29, 2020. It is now read-only.

Optimize Option[A] as A | Null #51

@sir-wabbit

Description

@sir-wabbit

As discussed with @Odomontois on Telegram, in non-polymorphic context, Option[A] can be replaced with A | Null (primitives would have to be replaced with their Java counterparts in Scala2).

Consider the following function, that computes the maximum value of all odd numbers in a list:

def maxOdd(l: List[Int]): Option[Int] = {
  def go(l: List[Int], sum: Option[Int]): Option[Int] = l match {
    case Nil => sum
    case x :: xs if x % 2 == 0 => go(xs, sum)
    case x :: xs => sum match {
      case None => go(xs, Some(x))
      case Some(y) => go(xs, Some(x max y))
    }
  }

  go(l, None)
}

We can optimize it as (Integer here plays the role of Int | Null):

def maxOdd(l: List[Int]): Option[Int] = {
  def go(l: List[Int], sum: Integer): Integer = l match {
    case Nil => sum
    case x :: xs if x % 2 == 0 => go(xs, sum)
    case x :: xs => sum match {
      case null => go(xs, x)
      case y => go(xs, x max y)
    }
  }

  Option(go(l, null))
}

This sort of rewriting should only be applied locally and to private functions.

Metadata

Metadata

Assignees

No one assigned

    Labels

    optimizationCode optimization opportunity.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions