Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 500951
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T06:08:23+00:00 2026-05-13T06:08:23+00:00

In Scala, I’d like to be able to write generic classes which use operators

  • 0

In Scala, I’d like to be able to write generic classes which use operators like >, /, * etc, but I don’t see how to constrain T such that this will work.

I looked into constraining T with Ordered[T], but that doesn’t seem to work since only RichXXX (e.g. RichInt) extend it, not Int etc. I also saw Numeric[T], is this only available in Scala 2.8?

Here is a specific example:

class MaxOfList[T](list: List[T] ) {
  def max = {
    val seed: Option[T] = None

    list
      .map( t => Some(t))
      // Get the max      
      .foldLeft(seed)((i,m) => getMax(i,m) )
  }

  private def getMax(x: Option[T], y: Option[T]) = {
    if ( x.isDefined && y.isDefined )
      if ( x > y ) x else y
    else if ( x.isDefined )
      x
    else
      y
  }
}

This class won’t compile, because there are many Ts which don’t support > etc.

Thoughts?

For now I’ve used a MixIn trait to get around this:

/** Defines a trait that can get the max of two generic values
 */
trait MaxFunction[T] {
  def getMax(x:T, y:T): T
}

/** An implementation of MaxFunction for Int
 */
trait IntMaxFunction extends MaxFunction[Int] {
  def getMax(x: Int, y: Int) = x.max(y)
} 

/** An implementation of MaxFunction for Double
 */
trait DoubleMaxFunction extends MaxFunction[Double] {
  def getMax(x: Double, y: Double) = x.max(y)
} 

Which if we alter the original class can be mixed in at instantiation time.

P.S. Mitch, inspired by your re-write of getMax, here is another:

  private def getMax(xOption: Option[T], yOption: Option[T]): Option[T] = (xOption,yOption) match {
    case (Some(x),Some(y)) => if ( x > y ) xOption else yOption
    case (Some(x), _) => xOption
    case _ => yOption
  }
  • 1 1 Answer
  • 1 View
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T06:08:23+00:00Added an answer on May 13, 2026 at 6:08 am

    You can use View Bounds.

    In short, def foo[T <% U](t: T) is a function that will take any T that either is or can be implicitly converted to a U. Since an Int can be converted to a RichInt (which contains your desired method), this is an excellent example of usage.

    class MaxOfList[T <% Ordered[T]](list: List[T] ) {
      def max = {
        val seed: Option[T] = None
        list.foldLeft(seed)(getMax(_,_))
      }
    
      private def getMax(xOption: Option[T], y: T) = (xOption, y) match {
        case (Some(x), y) if ( x > y ) => xOption
        case (_, y) => Some(y)
      }
    }
    

    PS – I rewrote your getMax(…) method to compare the values instead of the options themselves, and used pattern matching instead of isDefined(…)

    PPS – Scala 2.8 will have a Numeric trait that may be of use. http://article.gmane.org/gmane.comp.lang.scala/16608


    Addendum

    Just for giggles, here’s the super-compact version that eliminates the getMax method altogether:

    class MaxOfList[T <% Ordered[T]](list: List[T] ) {
      def max = list.foldLeft(None: Option[T]) {
          case (Some(x), y) if ( x > y ) => Some(x)
          case (_, y) => Some(y)
      }
    }
    

    Yet Another Addendum

    This version would be more efficient for large lists… avoids creation of Some(x) for each element:

    class MaxOfList[T <% Ordered[T]](list: List[T] ) {
      def max = {
        if (list.isEmpty) None
        else Some(list.reduceLeft((a,b) => if (a > b) a else b))
      }
    }
    

    Last One, I Promise!

    At this point, you can just ditch the class and use a function:

      def max[T <% Ordered[T]](i: Iterable[T]) = {
        if (i.isEmpty) None
        else Some(i.reduceLeft((a,b) => if (a > b) a else b))
      }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 476k
  • Answers 476k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Whenever you are dealing with XML, use XPath (or XSLT,… May 16, 2026 at 4:53 am
  • Editorial Team
    Editorial Team added an answer Check out Image resizing in .Net with Antialiasing, this should… May 16, 2026 at 4:53 am
  • Editorial Team
    Editorial Team added an answer <?php // test document, registrant as first/last element and somewhere… May 16, 2026 at 4:53 am

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.