jonderry
jonderry

Reputation: 23633

Best way to write a generic method that checks whether a number is 0 in scala

I know this is very trivial to do with a simple case check, but it seems it should be possible to write a method that does something like the following, that is generalizes to all numeric types:

  def checkNonZero(t: Long, field: String): List[String] = {
    if (t == 0) println("was zero") else println("wasn't zero")
  }

What's the best way to do this?

Upvotes: 2

Views: 104

Answers (2)

Electric Coffee
Electric Coffee

Reputation: 12124

An alternative way to Jasper-M's second solution goes as follows:

def isNotZero[A](n: A)(implicit num: Numeric[A]) = !num.equiv(n, num.zero)

This saves the line val num = implicitly[Numeric[A]], while still allowing you to work with num if you so desire.

Despite this method actually taking 2 parameters, because the second one's implicit, you can use it like you would any other non-curried single-parameter method:

isNotZero(3) // true
isNotZero(0.1) // true
isNotZero(0) // false
isNotZero(0.0) // false

Upvotes: 3

Jasper-M
Jasper-M

Reputation: 15086

This can be done with the Number type.

def checkNonZero(n: Number) = n != 0

Or you can use the Numeric typeclass.

def checkNonZero[T : Numeric](n: T) = { 
  val num = implicitly[Numeric[T]]
  !num.equiv(n, num.zero)
}

EDIT
Actually, you can just write it like this:

def checkNonZero[T : Numeric](n: T) = n != 0

Unless you define new custom instances of Numeric of course.

Upvotes: 6

Related Questions