Implicits bug (or feature)?

View: New views
1 Messages — Rating Filter:   Alert me  

Implicits bug (or feature)?

by Tim Azzopardi :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Latest nightly snapshot 2.8

I don't think the code below should compile, if SomeOtherPersonOrderingObjectInadvertentlyImported is commented back in, as there is an ambiguous implicit for the call to sortBy. But it compiles and changes the behaviour of:

people.sortBy(person => person)

to use SomeOtherPersonOrderingObjectInadvertentlyImported rather than the "natural" ordering provided through the Ordered[Person] defined on People.

I think the compiler should say that there is an ambiguous implicit parameter available for

people.sortBy(person => person) .

But it doesn't.





import org.scala_tools.time.Imports._

object TestSortBy {
  case class Person(firstName: String, lastName: String, dateOfBirth: DateTime)
    extends Ordered[Person]
  {
    override def toString() = {
      firstName + ", " + lastName + " " + DateTimeFormat.shortDate().print(dateOfBirth);
    }
    def compare(otherPerson: Person) = {
      lastName.compareTo(otherPerson.lastName)
    }
  }

  // Comment this is and watch the behaviour change. This could be imported accidentally
  // implicit object SomeOtherPersonOrderingObjectInadvertentlyImported
  //   extends Ordering[Person] {
  //   def compare(p1: Person, p2: Person) =
  //    (p1.firstName+p1.lastName).compareTo(p2.firstName+p2.lastName)
  // }

 
  def main(args : Array[String]) : Unit = {
   
    val people =
      Person("Alan", "Kay", new DateTime(1973,12,1,0,0,0,0))::
      Person("James", "Gosling", new DateTime(1991,12,1,0,0,0,0))::
      Person("Anders", "Hejlsberg", new DateTime(1999,12,1,0,0,0,0))::
      Person("Martin", "Odersky", new DateTime(2000,12,1,0,0,0,0))::
      Person("Guido", "Van Rossum", new DateTime(2002,12,1,0,0,0,0))::
      Person("Yukihiro", "Matsumoto", new DateTime(1990,12,1,0,0,0,0))::Nil
   
   
    val peopleOrderedNaturally = people.sortWith((p1,p2) => p1 < p2)
    peopleOrderedNaturally foreach println
    println

    val peopleOrderedNaturallyWithSortBy = people.sortBy(person => person)
    peopleOrderedNaturallyWithSortBy foreach println
    println    

  }

}