Rectangle 27 0

My personal favorite method is to make use of the provided implicit ordering for Tuples, as it is clear, concise, and correct:

case class A(tag: String, load: Int) extends Ordered[A] {
  // Required as of Scala 2.11 for reasons unknown - the companion to Ordered
  // should already be in implicit scope
  import scala.math.Ordered.orderingToOrdered

  def compare(that: A): Int = (this.tag, this.load) compare (that.tag, that.load)

This works because the companion to Ordered defines an implicit conversion from Ordering[T] to Ordered[T] which is in scope for any class implementing Ordered. The existence of implicit Orderings for Tuples enables a conversion from TupleN[...] to Ordered[TupleN[...]] provided an implicit Ordering[TN] exists for all elements T1, ..., TN of the tuple, which should always be the case because it makes no sense to sort on a data type with no Ordering.

The implicit ordering for Tuples is your go-to for any sorting scenario involving a composite sort key:

as.sortBy(a => (a.tag, a.load))

As this answer has proven popular I would like to expand on it, noting that a solution resembling the following could under some circumstances be considered enterprise-grade:

case class Employee(id: Int, firstName: String, lastName: String)

object Employee {
  // Note that because `Ordering[A]` is not contravariant, the declaration
  // must be type-parametrized in the event that you want the implicit
  // ordering to apply to subclasses of `Employee`.
  implicit def orderingByName[A <: Employee]: Ordering[A] = => (e.lastName, e.firstName))

  val orderingById: Ordering[Employee] = =>
es: SeqLike[Employee]
  • The sorts are defined in a single location as visible code artifacts. This is useful if you have complex sorts on many fields.
  • Most sorting functionality implemented in the scala library operates using instances of Ordering, so providing an ordering directly eliminates an implicit conversion in most cases.

You are welcome! I kept my example simple for clarity, but in cases where you sort by many fields, I would perhaps separate key extraction out into a protected def sortKey.

No need for a separate sortKey ... A.unapply _ is a function of type A => Option[(String, Int)]. Mutatis mutandis for every other case class.

value compare is not a member of (String, Int)

scala - easy idiomatic way to define Ordering for a simple case class ...

scala case-class
Rectangle 27 0

You can't mix in Ordered in this case, afaik... I tried it and ran into difficulties because compareTo is defined both there and in java.lang.Comparable. The compiler complains that Ordered doesn't use override in its definition of the method; I don't know how to get around that.

So define an implicit Ordering[Date]. You can put this DateOrdering object anywhere (e.g. in companion object).

import java.util.Date
implicit object DateOrdering extends Ordering[Date] {
  def compare(x: Date, y: Date) = x compareTo y

Then in your code:

import DateOrdering._
val a = new Date
val b = new Date
println(a < b)     // prints true
println(a >= b)    // prints false

The Ordering object contains an implicit def mkOrderingOps (lhs: T): Ops. The Ops class contains the <. >= etc methods, and this implicit def is an example of the pimp my library pattern on whatever the type parameter of the Ordering is (here, any Date instance).

scala - Idiomatic use of a Java comparable object - Stack Overflow

scala scala-java-interop
Rectangle 27 0

You could use the filterNot method.

val data = "test"
list = List("this", "is", "a", "test")
list.filterNot(elm => elm == data)

This will remove all elements that are equal to "test" - not what is asked for ;)

Actually it will do exactly what you need. It will return all elements from the list except those which aren't equal to "test". Pay attention that it uses filterNot

The original question was how to remove a SINGLE instance. Not all instances.

What is an idiomatic Scala way to "remove" one element from an immutab...

list scala
Rectangle 27 0

It's hard to use scala with null. And you can't get idiomatic scala code with while.

You have @Nullable and @NotNull - in scala it is Option[T] and T. You could replace while with recursive method.

getParentOfType[T <: PsiElement](element: Option[PsiElement],
                                 aClass: Class[T],
                                 strict: Boolean,
                                 stopAt: Class[_ <: PsiElement]*): Option[T] = element flatMap { el =>
  @tailrec def loop(element: PsiElement): Option[PsiElement] {
    if (element == null || aClass.isInstance(element))
    else if (instanceOf(element, stopAt) || element.isInstanceOf[PsiFile])

  loop(if (strict) el.getParent() else el).map{_.asInstanceOf[T]}

How do I write this method in Scala, or what is the best way to deal w...

Rectangle 27 0

I know you've already accepted an answer, but in you can use collectFirst to do find and map in one step:

def findBySqlName(sqlName : String) = {
  map.collectFirst({ case (cname, col) if (col.sqlName == sqlName) => col._2 })

Clean/idiomatic/concise way to return an Option from a map in Scala - ...

Rectangle 27 0

You would not do it like that in Scala. Why try to emulate something that can never work properly given JVM restrictions? Try idiomatic Scala instead:

trait Fooable[T] {
  def foo : Unit

object IntListFoo extends Fooable[List[Int]] {
  def foo {
    println("I just print")

class DoubleListFoo(val l : List[Double]) extends Fooable[List[Double]] {
  def foo {
    println("I iterate over list and print it.")
    l.foreach { e =>

implicit def intlist2fooable(l : List[Int]) = IntListFoo
implicit def doublelist2fooable(l : List[Double]) = new DoubleListFoo(l)

Then, you can execute code like


Scala: Method overloading over generic types - Stack Overflow

generics scala manifest reification
Rectangle 27 0

Put both types in a common package, it can be anywhere in the package hierarchy and doesn't have to be an immediate parent.


Is this the only way? In my case this has the effect of making the code accessible to the whole program. The package layout is already long established and rejiggering just for this would mess many other things up.

inheritance - idiomatic way to declare protected method in Scala when ...

scala inheritance composition protected idiomatic
Rectangle 27 0

The unapply method of the companion object provides a conversion from your case class to an Option[Tuple], where the Tuple is the tuple corresponding to the first argument list of the case class. In other words:

case class Person(name : String, age : Int, email : String)

def sortPeople(people : List[Person]) = 

scala - easy idiomatic way to define Ordering for a simple case class ...

scala case-class
Rectangle 27 0

  • For one-off sorting use .sortBy method, as @Shadowlands have showed
  • For reusing of sorting extend case class with Ordered trait, as @Keith said.
  • Define a custom ordering. The benefit of this solution is that you can reuse orderings and have multiple ways to sort instances of the same class: case class A(tag:String, load:Int) object A { val lexicographicalOrdering = { foo: A => foo.tag } val loadOrdering = { foo: A => foo.load } } implicit val ord = A.lexicographicalOrdering val l = List(A("words",1), A("article",2), A("lines",3)).sorted // List(A(article,2), A(lines,3), A(words,1)) // now in some other scope implicit val ord = A.loadOrdering val l = List(A("words",1), A("article",2), A("lines",3)).sorted // List(A(words,1), A(article,2), A(lines,3))

No such thing exists for case classes, since it is not easy thing to roll off, given that field names are not known a-priory (at least without macros magic) and you can't access case class fields in a way other than by name/using product iterator.

scala - easy idiomatic way to define Ordering for a simple case class ...

scala case-class
Rectangle 27 0

The sortBy method would be one typical way of doing this, eg (sort on tag field):

scala> l.sortBy(_.tag)foreach(println)
l.sortBy( e => e._tag + " " + e._load + " " + ... )

If using sortBy, then yes, either that, or add/use a suitable function to/on the class (eg _.toString, or your own lexographically-significant custom method or external function).

Is there any standard function included in to the Scala that can do magic like List((2,1),(1,2)).sorted to the case class objects? I see no big difference between named tuples (case class == named tuple) and simple tuples.

The nearest I can get along those lines is to use the companion object's unapply method to get an Option[TupleN], then call get on that: l.sortBy(A.unapply(_).get)foreach(println), which uses the provided ordering on the corresponding tuple, but this is simply an explicit example of the general idea I give above.

scala - easy idiomatic way to define Ordering for a simple case class ...

scala case-class
Rectangle 27 0

First of all, the behavior of the methods you presented is not the same. The first one keeps the element ordering, while the second one doesn't.

Second, among all the possible solution which could be qualified as "idiomatic", some are more efficient than others. Staying very close to your example, you can for instance use tail-recursion to eliminate variables and manual state management:

def removeMax1( xs: List[Int] ) = {
  def rec( max: Int, rest: List[Int], result: List[Int]): List[Int] = {
    if( rest.isEmpty ) result
    else if( rest.head > max ) rec( rest.head, rest.tail, max :: result)
    else rec( max, rest.tail, rest.head :: result )
  rec( xs.head, xs.tail, List() )

or fold the list:

def removeMax2( xs: List[Int] ) = {
  val result = xs.tail.foldLeft( xs.head -> List[Int]() ) { 
    (acc,x) =>
      val (max,res) = acc
      if( x > max ) x -> ( max :: res )
      else max -> ( x :: res )

If you want to keep the original insertion order, you can (at the expense of having two passes, rather than one) without any effort write something like:

def removeMax3( xs: List[Int] ) = {
  val max = xs.max
  xs.filterNot( _ == max )

Yes that's correct. Since the real intent was not precised, I'll let the example as it is.

Sadly, this answer is undervoted, given it presents the second fastest solution of all (the fastest one being the one presented as being "slow" in the question).

performance - Is Scala idiomatic coding style just a cool trap for wri...

scala performance
Rectangle 27 0

In general the scala collection classes define factory methods in their companion object using the apply method. The List("this","is","a","list") and Map("foo" -> 45, "bar" ->76) are syntactic sugar for calling those apply methods. Using this convention is fairly idiomatic scala.

In addition if you define a case class C(i: Int) it also defines a factory C.apply(i: Int) method which can be called as C(i). So no new needed.

Other than that, the new is required to create objects.

new operator - When is new required in scala - Stack Overflow

scala new-operator
Rectangle 27 0

You could use sealed class + case object. The only part you can't get with this approach is method values, but you could use this answer to implement method values like this:

sealed class Status(val code: Int, val name: String, val description: String)
object Status {
  def values: Set[Status] = macro SealedExample.values_impl[Status]

  case object OK extends Status(1, "Ok", "Okay")
  case object NOT_OK extends Status(5, "Not Ok", "Not Okay")
  case object BAD extends Status(10, "Bad", "Run for your life")

def doStuff(status: Status) = println(status.description)

for {s <- Status.values}
// Okay
// Not Okay
// Run for your life

Scala/Java enumerations - Stack Overflow

java scala enums idiomatic
Rectangle 27 0

I think you should expose only Option[String] in factory method. For example I, as a user of your library, will also ask myself question which factory method I should use. And most probably I will use Option.

Scala gives us enough tools to make our lifes easier. For example you can use default for option like this:

def apply(name: String, alpha3Code: String, alpha2Code: Option[String] = None) = 
 new Language(name, alpha3Code, alpha2Code)

If I, again as user of your library, want to pass just string without wrapping it in Some each time, I can write my own implicit conversion like this:

implicit def anyToOption[T](t: T): Option[T] = 
 if (t == null) None else Some(t)

Actually, there is an easier way to wrap an object in Option such that a null value will become None: Option(t) (instead of Some(t))

pattern matching - Idiomatic way to use Options's in Scala - Stack Ove...

scala pattern-matching equals tostring options
Rectangle 27 0

The idiomatic way to write nested pattern matching with options in Scala is by using the methods map, flatMap, orElse, and getOrElse.

You use map when you want to process the content of the option further and keep the optional behaviour:

You would do this:

val opt: Option[Int] = ??? + 1) + 1).map(_ * 3).map(_ - 2)

flatMap is verlly similar, but is used when your further operations return an option type as well.

In your particular example, orElse seems to be the most adapted solution. You can use orElse to return the option itself if not empty or else return the argument. Note that the argument is lazily evaluated so it is really equivalent to nested pattern matching/if-then-else.

You can also combine these with getOrElse if you want to get rid of an Option. In your example you seem to return the final f4 as if it did not return an Option, so you would do the following:

def foo = {

coding style - Idiomatic Scala for Options in place of if/else/else ch...

scala coding-style optional
Rectangle 27 0

Scala generally favors typed data and immutability, and you're fighting against both of those here. I don't know what the context is for this map, but I think it would be more idiomatic to use a case clase with optional parameters. For example:

case class Person(name: String, age: Option[Int], children: Seq[Person]) {
  def hasChildren: Boolean = !children.isEmpty

Now you might call this as follows with an optional name variable.

val name: Option[String] = Option("suud")
val age: Option[Int] = Option(25)
val children: Seq[Person] = Seq.empty
val suud: Option[Person] = name map {Person(_, age, children)}

The way that foo is written, it's possible to pass in an empty list of children with a boolean parameter which says the map has children. Writing hasChildren as a method of a case class guards against this, because the boolean method depends on the collection it's meant to provide information about.

If you really insist on using a map here, you can either use a MapBuilder to get an immutable map, or just import and use the mutable map.

Now the result of the builder is an immutable map. If you really need a mutable map, you can just:

import scala.collection.mutable

val m = mutable.Map[String, Any]()

Now you've got a mutable map which can be converted to an immutable map with its toMap method.

Need help to refactor this scala method in functional programming styl...

scala functional-programming
Rectangle 27 0

@LimbSoup's answer is definitely appropriate for a case where you're simply calling a side-effectful function with no return type. For the sake of completeness, here are few other ways to work with Option values in Scala. When working with functions that return a value, you've correctly identified one of the more idiomatic methods, using the map function:

val optX : Option[Int] = Some(1)
optX map { _ + 1 }    // returns Some[Int](2)

val optY : Option[Int] = None
optY map { _ + 1 }    // returns None

This behavior extends to other functions like filter and fold. As syntactic sugar, you can also use a for comprehension, the same way you would on a list.

for (x <- optX) yield (x + 1)  // desugars to ' + 1)'
for (x <- optX) doSomething(x) // desugars to 'optX.foreach(x => doSomething(x))'

If you want to use Options a bit more in the vein of how you would in Java, you would typically write a pattern matching statement, as follows:

optX match {
  case Some(x) => doSomething(x)
  case None    => doSomethingElse()

This is good for when you want an if/else sort of behavior, rather than executing or not executing a function based on whether or not you have a value.

When working with a sequence of Options, you can strip out the None values by using flatMap.

// Applies a map to only the types with values
Seq(Some(1), Some(2), Some(3), None, None, None, Some(4)) flatMap { _ + 1 }  // returns Seq(2, 3, 4, 5)

Lastly, you can completely throw caution to the wind and call .get on your Option type. You probably shouldn't, but it's available to you. This will either return the unwrapped value, in case of a 'Some', or throw an exception in case of 'None'.

functional programming - correct usage of scala map - Stack Overflow

scala functional-programming
Rectangle 27 0

.collectFirst{ case RateRegex(x) => x.toDouble}

Not sure if it's more functional, but you can use the behaviour of foreach/for-comprehensions on Options

def getRate(source : Source) : Option[Double] = {

     for {line    <- source.getLines() 
          rawRate <- RateRegex.findFirstIn(line)}
       return  Some(rawRate toDouble)

  return None

The last three are a little ugly. The take(1) is to ensure we only evaluate up to the first match. The toList is to force the evaluation, and the headOption to extract the first value as Some() or None if there is none. Is there a more idiomatic way of doing this?

Nice! Is it possible to replace rawRate <- RateRegex.findFirstIn(line) with RateRegex(rawMatch) <- line? I tried it but now I always return None. Much easier that way, since the target number is in a match group.

rawRate <- findFirstIn
match <- findFirstMatchIn

Unfortunately headOption is not defined neither in Iterator nor in TraversableOnce (it's defined in TraversableLike though). Also in your second map, argument is of type Option[Regex.Match], so it will not compile.

@EasyAngel, yes, removed the alternative. There's got to be something similar that should work, though. I'll think about it a bit harder.

I updated my question with a solution based on the Groups extractor. Using the RateRegex(rawRate) pattern on the LHS of the for pattern doesn't seem to work, even though it should be returning an Option[List[String]]. But with the RateRegex extractor, the body of the for loop is never executed.

Idiomatic way to find a matching line in Scala - Stack Overflow

Rectangle 27 0

It sounds like you want find and foreach (you appear to be applying a side-effecting function) :

list.find( == value).foreach { foo =>

Ah, find! that's what I didn't know about

Idiomatic scala collectFirst method? - Stack Overflow

Rectangle 27 0

This solution does not work for general Maps, but if you are using immutable.HashMaps you may consider the merged method:

def merged[B1 >: B](that: HashMap[A, B1])(mergef: ((A, B1), (A, B1))  (A, B1)): HashMap[A, B1]

Creates a new map which is the merge of this and the argument hash map.

Uses the specified collision resolution function if two keys are the same. The collision resolution function will always take the first argument from this hash map and the second from that.

The merged method is on average more performant than doing a traversal and reconstructing a new immutable hash map from scratch, or ++.

val m1 = immutable.HashMap[Int, Int](1 -> 2, 2 -> 3)
val m2 = immutable.HashMap[Int, Int](1 -> 3, 4 -> 5)
m1.merged(m2) {
  case ((k1, v1), (k2, v2)) => ((k1, math.max(v1, v2)))

Scala: idiomatic way to merge list of maps with the greatest value of ...

scala scala-collections reduce scalaz