Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help understanding usage of ->, {} and () in this code

Tags:

scala

Here is the piece of code in question:

val oauth_params = IMap(
      "oauth_consumer_key" -> consumer.key,
      "oauth_signature_method" -> "HMAC-SHA1",
      "oauth_timestamp" -> (System.currentTimeMillis / 1000).toString,
      "oauth_nonce" -> System.nanoTime.toString
    ) ++ token.map { "oauth_token" -> _.value } ++
      verifier.map { "oauth_verifier" -> _ }

Question 1: What Scala feature enabled "oauth_consumer_key" -> consumer.key to exist and passed as arguments?

Question 2: Seeing val oauth_params = IMap(...) and token.map {...}, which operations use {} for passing values rather than the usual ()? Are there specific rules? And why is the for loop allowed to use both, if it is a related issue?

I ask here as I saw the features being used elsewhere. I also believe that both questions are related.

like image 365
Jesvin Jose Avatar asked Jul 10 '12 13:07

Jesvin Jose


1 Answers

In order:

-> is defined in Predef.scala, which is imported inside any other Scala source during the compilation:

final class ArrowAssoc[A](val x: A) {
  @inline def -> [B](y: B): Tuple2[A, B] = Tuple2(x, y)
  def →[B](y: B): Tuple2[A, B] = ->(y)
}
implicit def any2ArrowAssoc[A](x: A): ArrowAssoc[A] = new ArrowAssoc(x)

As you can see, there is an implicit conversion that convert any object into an ArrowAssoc[A], which has a method ->[B] which returns a Tuple2[A,B].

IMap(...) it's the call to the method IMap.apply(...) : in Scala if a method is named apply, you can omit it. In this case, it is used as a factory method in a very common pattern in Scala

class MyClass(....) {

}
object MyClass{ 
   def apply(....): MyClass = new MyClass(....)
}

val a = MyClass(a,b,c)

What you just saw is a Scala class and its companion object: a singleton which has to be defined in the same source file as the class and which can also access private and protected fields in the the class itself

The map function receives a function which takes the same type of the collection and returns a different type. Example: List(1,2,3).map ( x => x * 2). ( ) and { } are interchangeable in Scala excepts with the case construct.

like image 130
Edmondo1984 Avatar answered Oct 17 '22 06:10

Edmondo1984