whatsnext
whatsnext

Reputation: 627

How to write a scala function to accept arguments with two types?

I have two functions:

def capPredDouble(rawPred: Double): Double = {
  if (label == "1") {
    Math.min(1.0, rawPred)
  } else {
    Math.max(0, rawPred)
  }
}


def capPred(rawPred: Float): Float = {
  if (label == "1") {
    Math.min(1.0f, rawPred)
  } else {
    Math.max(0, rawPred)
  }
}

Is that possible to use polymorphism to make them one function?

Upvotes: 2

Views: 253

Answers (1)

jwvh
jwvh

Reputation: 51271

This appears to work.

def capPred[N](rawPred :N)(implicit ev :Numeric[N]) :N =
  if (<some condition>) ev.min(ev.one,  rawPred)
  else                  ev.max(ev.zero, rawPred)

Upvotes: 3

Related Questions