jamborta
jamborta

Reputation: 5210

Define upper bound type to allow arithmetic operations

Is it possible to define a upper bound type that would allow the basic arithmetic operations in the function? Simply to make this work:

def a[T](t:T):T = {t*t}

Upvotes: 1

Views: 110

Answers (3)

jamborta
jamborta

Reputation: 5210

Also found a similar solution (that allows division, too)

import scala.math.Integral.Implicits._  

def a[T:Integral](t:T):T = t * t / t

Upvotes: 0

user3248346
user3248346

Reputation:

The Scala spire library is awesome. It provides many types of numeric abstractions.

import spire.math._
import spire.implicits._

def negate[A: Integral](x: A) = -(42 * (x /~ 42) + x % 42)

Upvotes: 1

Michael Zajac
Michael Zajac

Reputation: 55569

There is no common super-type for all possible numeric types in Scala, so I would use the Numeric trait. It isn't a type bound, but rather a type class where you can require an implicit Numeric[A] be available in scope. Implicits already exist in scope for all of Scala's numeric types.

def a[T](t: T)(implicit num: Numeric[T]): T = num.times(t, t)

Or

def a[T: Numeric](t: T): T = implicitly[Numeric[T]].times(t, t)

Upvotes: 2

Related Questions