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

  • Home
  • SEARCH
  • 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 8585393
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T22:03:06+00:00 2026-06-11T22:03:06+00:00

I’m new to Scala. I’m using SortedMap in my code, and I wanted to

  • 0

I’m new to Scala.
I’m using SortedMap in my code, and I wanted to use mapValues to create a new map with some transformation on the values.

Instead of returning a new SortedMap, the mapValues function returns a new Map, which I then have to convert to a SortedMap.

For example

val my_map = SortedMap(1 -> "one", 0 -> "zero", 2 -> "two")
val new_map = my_map.mapValues(name => name.toUpperCase)
// returns scala.collection.immutable.Map[Int,java.lang.String] = Map(0 -> ZERO, 1 -> ONE, 2 -> TWO)
val sorted_new_map = SortedMap(new_map.toArray:_ *)

This looks inefficient – the last convertion probably sorts the keys again, or at least verify that they are sorted.

I could use the normal map function which operates both on the keys and the values, and deliberately not change the keys in my transformation function. This looks inefficient too, since the implementation of Map probably assume that the transformation may change the order of the keys (like in the case: my_map.map(tup => (-tup._1, tup._2)) – so it probably “re-sorts” them too.

Is anyone familiar with the internal implementations of Map and SortedMap, and could tell me if my assumptions are correct? Can the compiler recognize automatically that the keys have not been reordered? Is there an internal reason for why mapValues should not return a SortedMap? Is there a better way to transform the map’s values without loosing the order of the keys?

Thanks

  • 1 1 Answer
  • 0 Views
  • 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-06-11T22:03:08+00:00Added an answer on June 11, 2026 at 10:03 pm

    You’ve stumbled upon a tricky feature of Scala’s Map implementation. The catch that you are missing is that mapValues does not actually return a new Map: it returns a view of a Map. In other words, it wraps your original map in such a way that whenever you access a value it will compute .toUpperCase before returning the value to you.

    The upside to this behavior is that Scala won’t compute the function for values that aren’t accessed, and it won’t spend time copying all the data into a new Map. The downside is that the function is re-computed every time that value is accessed. So you might end up doing extra computation if you access the same values many times.

    So why does SortedMap not return a SortedMap? Because it’s actually returning a Map-wrapper. The underlying Map, then one that is wrapped, is still a SortedMap, so if you were to iterate through, it would still be in sorted order. You and I know that, but the type-checker doesn’t. It certainly seems like they could have written it in such a way that it still maintains the SortedMap trait, but they didn’t.

    You can see in the code that it’s not returning a SortedMap, but that the iteration behavior is still going to be sorted:

    // from MapLike
    override def mapValues[C](f: B => C): Map[A, C] = new DefaultMap[A, C] {
      def iterator = for ((k, v) <- self.iterator) yield (k, f(v))
      ...
    

    The solution to your problem is the same as the solution to getting around the view issue: use .map{ case (k,v) => (k,f(v)) }, as you mentioned in your question.


    If you really want that convenience method though, you can do what I do, and write you own, better, version of mapValues:

    class EnrichedWithMapVals[T, U, Repr <: GenTraversable[(T, U)]](self: GenTraversableLike[(T, U), Repr]) {
      /**
       * In a collection of pairs, map a function over the second item of each
       * pair.  Ensures that the map is computed at call-time, and not returned
       * as a view as 'Map.mapValues' would do.
       *
       * @param f   function to map over the second item of each pair
       * @return a collection of pairs
       */
      def mapVals[R, That](f: U => R)(implicit bf: CanBuildFrom[Repr, (T, R), That]) = {
        val b = bf(self.asInstanceOf[Repr])
        b.sizeHint(self.size)
        for ((k, v) <- self) b += k -> f(v)
        b.result
      }
    }
    implicit def enrichWithMapVals[T, U, Repr <: GenTraversable[(T, U)]](self: GenTraversableLike[(T, U), Repr]): EnrichedWithMapVals[T, U, Repr] =
      new EnrichedWithMapVals(self)
    

    Now when you call mapVals on a SortedMap you get back a non-view SortedMap:

    scala> val m3 = m1.mapVals(_ + 1)
    m3: SortedMap[String,Int] = Map(aardvark -> 2, cow -> 6, dog -> 10)
    

    It actually works on any collection of pairs, not just Map implementations:

    scala> List(('a,1),('b,2),('c,3)).mapVals(_+1)
    res8: List[(Symbol, Int)] = List(('a,2), ('b,3), ('c,4))
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm new to using the Perl treebuilder module for HTML parsing and can't figure
I want use html5's new tag to play a wav file (currently only supported
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text
I am trying to understand how to use SyndicationItem to display feed which is
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am reading a book about Javascript and jQuery and using one of the
I have this code to decode numeric html entities to the UTF8 equivalent character.

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.