Scala.js Warts

Build Status Maven Central

WartRemover warts for Scala.js.

Versions

Scala.js Warts version WartRemover version Scala.js version Scala version
0.4.0 2.0.1 0.6.14 2.11.8, 2.12.1

Usage

  1. Setup WartRemover.

  2. Add the following to your plugins.sbt:

    addSbtPlugin("org.danielnixon" % "sbt-scalajswarts" % "0.4.0")
  3. Add the following to your build.sbt:

    wartremoverWarnings ++= Seq(
      ScalaJSWart.ArrayPartial,
      ScalaJSWart.UndefOrOpsPartial
    )

Warts

ArrayPartial

scala.scalajs.js.Array[T] has apply, pop and shift methods, all of which can return undefined (even though their return type is T, not UndefOr[T]). This can lead to UndefinedBehaviorErrors.

You can wrap these methods in an implicit that might look something like this:

  @SuppressWarnings(Array("org.danielnixon.scalajswarts.ArrayPartial"))
  implicit class SaferArray[A](val value: scala.scalajs.js.Array[A]) extends AnyVal {
    def applyOpt(index: Int): Option[A] = liftUndefined(value.apply(index))

    def popOpt(): Option[A] = liftUndefined(value.pop())

    def shiftOpt(): Option[A] = liftUndefined(value.shift())

    private def liftUndefined[T <: scala.Any](v: T): Option[T] = {
      if (scalajs.js.isUndefined(v)) None else Some(v)
    }
  }

UndefOrOpsPartial

scala.scalajs.js.UndefOrOps has a get method which will throw if the value is undefined. The program should be refactored to use UndefOrOps#getOrElse or UndefOrOps#fold to explicitly handle both the defined and undefined cases.

See also