Scala interview questions
54 questions, 24 with answers. 247 open jobs in India ask for Scala.
Is the Scala 2.8 collections library a case of "the longest suicide note in history"?
I hope it's not a "suicide note", but I can see your point. You hit on what is at the same time both a strength and a problem of Scala: its extensibility. This lets us implement most major functionality in libraries. In some other languages, sequences with something like
maporcollectwould be built in, and nobody has to see all the hoops the compiler has to go through to make them work smoothly. In Scala, it's all in a library, and therefore out in the open.In fact the functionality of
mapthat's supported by its complicated type is pretty advanced. Consider this:scala> import collection.immutable.BitSet import collection.immutable.BitSet scala> val bits = BitSet(1, 2, 3) bits: scala.collection.immutable.BitSet = BitSet(1, 2, 3) scala> val shifted = bits map { _ + 1 } shifted: scala.collection.immutable.BitSet = BitSet(2, 3, 4) scala> val displayed = bits map { _.toString + "!" } displayed: scala.collection.immutable.Set[java.lang.String] = Set(1!, 2!, 3!)See how you always get the best possible type? If you map
Ints toInts you get again aBitSet, but if you mapInts toStrings, you get a generalSet. Both the static type and the runtime representation of map's result depend on the result type of the function that's passed to it. And this works even if the set is empty, so the function is never applied! As far as I know there is no other collection framework with an equivalent functionality. Yet from a user perspective this is how things are supposed to work.The problem we have is that all the clever technology that makes this happen leaks into the type signatures which become large and scary. But maybe a user should not be shown by default the full type signature of
map? How about if she looked upmapinBitSetshe got:map(f: Int => Int): BitSet (click here for more general type)The docs would not lie in that case, because from a user perspective indeed map has the type
(Int => Int) => BitSet. Butmapalso has a more general type which can be inspected by clicking on another link.We have not yet implemented functionality like this in our tools. But I believe we need to do this, to avoid scaring people off and to give more useful info. With tools like that, hopefully smart frameworks and libraries will not become suicide notes.
From Stack Overflow: asked by oxbow_lakes, answered by Martin Odersky (CC BY-SA 3.0)
Difference between object and class in Scala
tl;dr
class Cdefines a class, just as in Java or C++.object Ocreates a singleton objectOas instance of some anonymous class; it can be used to hold static members that are not associated with instances of some class.object O extends Tmakes the objectOan instance oftrait T; you can then passOanywhere, aTis expected.- if there is a
class C, thenobject Cis the companion object of classC; note that the companion object is not automatically an instance ofC.
Also see Scala documentation for object and class.
objectas host of static membersMost often, you need an
objectto hold methods and values/variables that shall be available without having to first instantiate an instance of some class. This use is closely related tostaticmembers in Java.object A { def twice(i: Int): Int = 2*i }You can then call above method using
A.twice(2).If
twicewere a member of some classA, then you would need to make an instance first:class A() { def twice(i: Int): Int = 2 * i } val a = new A() a.twice(2)You can see how redundant this is, as
twicedoes not require any instance-specific data.objectas a special named instanceYou can also use the
objectitself as some special instance of a class or trait. When you do this, your object needs to extend sometraitin order to become an instance of a subclass of it.Consider the following code:
object A extends B with C { ... }This declaration first declares an anonymous (inaccessible) class that extends both
BandC, and instantiates a single instance of this class namedA.This means
Acan be passed to functions expecting objects of typeBorC, orB with C.Additional Features of
objectThere also exist some special features of objects in Scala. I recommend to read the official documentation.
def apply(...)enables the usual method name-less syntax ofA(...)def unapply(...)allows to create custom pattern matching extractors- if accompanying a class of the same name, the object assumes a special role when resolving implicit parameters
From Stack Overflow: asked by Steve, answered by ziggystar (CC BY-SA 4.0)
Scala vs. Groovy vs. Clojure
Groovy is a dynamically typed language, whose syntax is very close to Java, with a number of syntax improvements that allow for lighter code and less boilerplate. It can run through an interpreter as well as being compiled, which makes it good for fast prototyping, scripts, and learning dynamic languages without having to learn a new syntax (assuming you know Java). As of Groovy 2.0, it also has growing support for static compilation. Groovy supports closures and has support for programming in a somewhat functional style, although it's still fairly far from the traditional definition of functional programming.
Clojure is a dialect of Lisp with a few advanced features like Software Transactional Memory. If you like Lisp and would like to use something like it under the JVM, Clojure is for you. It's possibly the most functional language running on the JVM, and certainly the most famous one. Also, it has a stronger emphasis on immutability than other Lisp dialects, which takes it closer to the heart of functional language enthusiasts.
Scala is a fully object oriented language, more so than Java, with one of the most advanced type systems available on non-research languages, and certainly the most advanced type system on the JVM. It also combines many concepts and features of functional languages, without compromising the object orientation, but its compromise on functional language characteristics put off some enthusiasts of the latter.
Groovy has good acceptance and a popular web framework in Grails. It also powers the Gradle build system, which is becoming a popular alternative to Maven. I personally think it is a language with limited utility, particularly as Jython and JRuby start making inroads on the JVM-land, compared to the others.
Clojure, even discounting some very interesting features, has a strong appeal just by being a Lisp dialect on JVM. It might limit its popularity, granted, but I expect it will have loyal community around it for a long time.
Scala can compete directly with Java, and give it a run for its money on almost all aspects. It can't compete in popularity at the moment, of course, and the lack of a strong corporate backing may hinder its acceptance on corporate environments. It's also a much more dynamic language than Java, in the sense of how the language evolves. From the perspective of the language, that's a good thing. From the perspective of users who plan on having thousands of lines of code written in it, not so.
As a final disclosure, I'm very familiar with Scala, and only acquainted with the other two.
From Stack Overflow: asked by James Fassett, answered by Daniel C. Sobral (CC BY-SA 3.0)
What are the best use cases for Akka framework?
I have used it so far in two real projects very successfully. both are in the near real-time traffic information field (traffic as in cars on highways), distributed over several nodes, integrating messages between several parties, reliable backend systems. I'm not at liberty to give specifics on clients yet, when I do get the OK maybe it can be added as a reference.
Akka has really pulled through on those projects, even though we started when it was on version 0.7. (we are using scala by the way)
One of the big advantages is the ease at which you can compose a system out of actors and messages with almost no boilerplating, it scales extremely well without all the complexities of hand-rolled threading and you get asynchronous message passing between objects almost for free.
It is very good in modeling any type of asynchronous message handling. I would prefer to write any type of (web) services system in this style than any other style. (Have you ever tried to write an asynchronous web service (server side) with JAX-WS? that's a lot of plumbing). So I would say any system that does not want to hang on one of its components because everything is implicitly called using synchronous methods, and that one component is locking on something. It is very stable and the let-it-crash + supervisor solution to failure really works well. Everything is easy to setup programmatically and not hard to unit test.
Then there are the excellent add-on modules. The Camel module really plugs in well into Akka and enables such easy development of asynchronous services with configurable endpoints.
I'm very happy with the framework and it is becoming a defacto standard for the connected systems that we build.
From Stack Overflow: asked by StaxMan, answered by Raymond Roestenburg (CC BY-SA 2.5)
What are all the uses of an underscore in Scala?
The ones I can think of are
Existential types
def foo(l: List[Option[_]]) = ...Higher kinded type parameters
case class A[K[_],T](a: K[T])Ignored variables
val _ = 5Ignored parameters
List(1, 2, 3) foreach { _ => println("Hi") }Ignored names of self types
trait MySeq { _: Seq[_] => }Wildcard patterns
Some(5) match { case Some(_) => println("Yes") }Wildcard patterns in interpolations
"abc" match { case s"a$_c" => }Sequence wildcard in patterns
C(1, 2, 3) match { case C(vs @ _*) => vs.foreach(f(_)) }Wildcard imports
import java.util._Hiding imports
import java.util.{ArrayList => _, _}Joining letters to operators
def bang_!(x: Int) = 5Assignment operators
def foo_=(x: Int) { ... }Placeholder syntax
List(1, 2, 3) map (_ + 2)Method values
List(1, 2, 3) foreach println _Converting call-by-name parameters to functions
def toFunction(callByName: => Int): () => Int = callByName _Default initializer
var x: String = _ // unloved syntax may be eliminatedGroup digits in numeric literals
15_000_000 // Equivalent to "15000000".There may be others I have forgotten!
Example showing why
foo(_)andfoo _are different:This example comes from 0__:
trait PlaceholderExample { def process[A](f: A => Unit) val set: Set[_ => Unit] set.foreach(process _) // Error set.foreach(process(_)) // No Error }In the first case,
process _represents a method; Scala takes the polymorphic method and attempts to make it monomorphic by filling in the type parameter, but realizes that there is no type that can be filled in forAthat will give the type(_ => Unit) => ?(Existential_is not a type).In the second case,
process(_)is a lambda; when writing a lambda with no explicit argument type, Scala infers the type from the argument thatforeachexpects, and_ => Unitis a type (whereas just plain_isn't), so it can be substituted and inferred.This may well be the trickiest gotcha in Scala I have ever encountered.
Note that this example compiles in 2.13. Ignore it like it was assigned to underscore.
From Stack Overflow: asked by Ivan, answered by Owen (CC BY-SA 4.0)
What is the difference between Scala's case class and class?
Case classes can be seen as plain and immutable data-holding objects that should exclusively depend on their constructor arguments.
This functional concept allows us to
- use a compact initialization syntax (
Node(1, Leaf(2), None))) - decompose them using pattern matching
- have equality comparisons implicitly defined
In combination with inheritance, case classes are used to mimic algebraic datatypes.
If an object performs stateful computations on the inside or exhibits other kinds of complex behaviour, it should be an ordinary class.
From Stack Overflow: asked by Teja Kantamneni, answered by Dario (CC BY-SA 4.0)
- use a compact initialization syntax (
What do all of Scala's symbolic operators mean?
I divide the operators, for the purpose of teaching, into four categories:
- Keywords/reserved symbols
- Automatically imported methods
- Common methods
- Syntactic sugars/composition
It is fortunate, then, that most categories are represented in the question:
-> // Automatically imported method ||= // Syntactic sugar ++= // Syntactic sugar/composition or common method <= // Common method _._ // Typo, though it's probably based on Keyword/composition :: // Common method :+= // Common methodThe exact meaning of most of these methods depend on the class that is defining them. For example,
<=onIntmeans "less than or equal to". The first one,->, I'll give as example below.::is probably the method defined onList(though it could be the object of the same name), and:+=is probably the method defined on variousBufferclasses.So, let's see them.
Keywords/reserved symbols
There are some symbols in Scala that are special. Two of them are considered proper keywords, while others are just "reserved". They are:
// Keywords <- // Used on for-comprehensions, to separate pattern from generator => // Used for function types, function literals and import renaming // Reserved ( ) // Delimit expressions and parameters [ ] // Delimit type parameters { } // Delimit blocks . // Method call and path separator // /* */ // Comments # // Used in type notations : // Type ascription or context bounds <: >: <% // Upper, lower and view bounds <? <! // Start token for various XML elements " """ // Strings ' // Indicate symbols and characters @ // Annotations and variable binding on pattern matching ` // Denote constant or enable arbitrary identifiers , // Parameter separator ; // Statement separator _* // vararg expansion _ // Many different meaningsThese are all part of the language, and, as such, can be found in any text that properly describe the language, such as Scala Specification(PDF) itself.
The last one, the underscore, deserve a special description, because it is so widely used, and has so many different meanings. Here's a sample:
import scala._ // Wild card -- all of Scala is imported import scala.{ Predef => _, _ } // Exception, everything except Predef def f[M[_]] // Higher kinded type parameter def f(m: M[_]) // Existential type _ + _ // Anonymous function placeholder parameter m _ // Eta expansion of method into method value m(_) // Partial function application _ => 5 // Discarded parameter case _ => // Wild card pattern -- matches anything f(xs: _*) // Sequence xs is passed as multiple parameters to f(ys: T*) case Seq(xs @ _*) // Identifier xs is bound to the whole matched sequenceI probably forgot some other meaning, though.
Automatically imported methods
So, if you did not find the symbol you are looking for in the list above, then it must be a method, or part of one. But, often, you'll see some symbol and the documentation for the class will not have that method. When this happens, either you are looking at a composition of one or more methods with something else, or the method has been imported into scope, or is available through an imported implicit conversion.
These can still be found on ScalaDoc: you just have to know where to look for them. Or, failing that, look at the index (presently broken on 2.9.1, but available on nightly).
Every Scala code has three automatic imports:
Read the rest at the sourceFrom Stack Overflow: asked by 0__, answered by Daniel C. Sobral (CC BY-SA 3.0)
Where does Scala look for implicits?
Types of Implicits
Implicits in Scala refers to either a value that can be passed "automatically", so to speak, or a conversion from one type to another that is made automatically.
Implicit Conversion
Speaking very briefly about the latter type, if one calls a method
mon an objectoof a classC, and that class does not support methodm, then Scala will look for an implicit conversion fromCto something that does supportm. A simple example would be the methodmaponString:"abc".map(_.toInt)Stringdoes not support the methodmap, butStringOpsdoes, and there's an implicit conversion fromStringtoStringOpsavailable (seeimplicit def augmentStringonPredef).Implicit Parameters
The other kind of implicit is the implicit parameter. These are passed to method calls like any other parameter, but the compiler tries to fill them in automatically. If it can't, it will complain. One can pass these parameters explicitly, which is how one uses
breakOut, for example (see question aboutbreakOut, on a day you are feeling up for a challenge).In this case, one has to declare the need for an implicit, such as the
foomethod declaration:def foo[T](t: T)(implicit integral: Integral[T]) {println(integral)}View Bounds
There's one situation where an implicit is both an implicit conversion and an implicit parameter. For example:
def getIndex[T, CC](seq: CC, value: T)(implicit conv: CC => Seq[T]) = seq.indexOf(value) getIndex("abc", 'a')The method
getIndexcan receive any object, as long as there is an implicit conversion available from its class toSeq[T]. Because of that, I can pass aStringtogetIndex, and it will work.Behind the scenes, the compiler changes
seq.IndexOf(value)toconv(seq).indexOf(value).This is so useful that there is syntactic sugar to write them. Using this syntactic sugar,
getIndexcan be defined like this:def getIndex[T, CC <% Seq[T]](seq: CC, value: T) = seq.indexOf(value)This syntactic sugar is described as a view bound, akin to an upper bound (
CC <: Seq[Int]) or a lower bound (T >: Null).Context Bounds
Another common pattern in implicit parameters is the type class pattern. This pattern enables the provision of common interfaces to classes which did not declare them. It can both serve as a bridge pattern -- gaining separation of concerns -- and as an adapter pattern.
The
Integralclass you mentioned is a classic example of type class pattern. Another example on Scala's standard library isOrdering. There's a library that makes heavy use of this pattern, called Scalaz.This is an example of its use:
def sum[T](list: List[T])(implicit integral: Integral[T]): T = { import integral._ // get the implicits in question into scope list.foldLeft(integral.zero)(_ + _) }There is also syntactic sugar for it, called a context bound, which is made less useful by the need to refer to the implicit. A straight conversion of that method looks like this:
def sum[T : Integral](list: List[T]): T = { val integral = implicitly[Integral[T]] import integral._ // get the implicits in question into scope list.foldLeft(integral.zero)(_ + _) }Context bounds are more useful when you just need to pass them to other methods that use them. For example, the method
sortedonSeqneeds an implicitOrdering. To create a methodreverseSort, one could write:def reverseSort[T : Ordering](seq: Seq[T]) = seq.sorted.reverseBecause
Ordering[T]was implicitly passed toreverseSort, it can then pass it implicitly tosorted.Where do Implicits come from?
Read the rest at the sourceFrom Stack Overflow: asked by Daniel C. Sobral, answered by Daniel C. Sobral (CC BY-SA 4.0)
What is the difference between self-types and trait subclasses?
It is predominately used for Dependency Injection, such as in the Cake Pattern. There exists a great article covering many different forms of dependency injection in Scala, including the Cake Pattern. If you Google "Cake Pattern and Scala", you'll get many links, including presentations and videos. For now, here is a link to another question.
Now, as to what is the difference between a self type and extending a trait, that is simple. If you say
B extends A, thenBis anA. When you use self-types,Brequires anA. There are two specific requirements that are created with self-types:- If
Bis extended, then you're required to mix-in anA. - When a concrete class finally extends/mixes-in these traits, some class/trait must implement
A.
Consider the following examples:
scala> trait User { def name: String } defined trait User scala> trait Tweeter { | user: User => | def tweet(msg: String) = println(s"$name: $msg") | } defined trait Tweeter scala> trait Wrong extends Tweeter { | def noCanDo = name | } <console>:9: error: illegal inheritance; self-type Wrong does not conform to Tweeter's selftype Tweeter with User trait Wrong extends Tweeter { ^ <console>:10: error: not found: value name def noCanDo = name ^If
Tweeterwas a subclass ofUser, there would be no error. In the code above, we required aUserwheneverTweeteris used, however aUserwasn't provided toWrong, so we got an error. Now, with the code above still in scope, consider:scala> trait DummyUser extends User { | override def name: String = "foo" | } defined trait DummyUser scala> trait Right extends Tweeter with User { | val canDo = name | } defined trait Right scala> trait RightAgain extends Tweeter with DummyUser { | val canDo = name | } defined trait RightAgainWith
Right, the requirement to mix-in aUseris satisfied. However, the second requirement mentioned above is not satisfied: the burden of implementingUserstill remains for classes/traits which extendRight.With
RightAgainboth requirements are satisfied. AUserand an implementation ofUserare provided.For more practical use cases, please see the links at the start of this answer! But, hopefully now you get it.
From Stack Overflow: asked by Dave, answered by Daniel C. Sobral (CC BY-SA 4.0)
- If
What is the advantage of using abstract classes instead of traits?
I can think of two differences:
- Abstract classes can have constructor parameters as well as type parameters. Traits can have only type parameters in Scala 2. In Scala 3, traits can have constructor parameters.
- Abstract classes are fully interoperable with Java. You can call them from Java code without any wrappers. Prior to Scala 2.12, traits were fully interoperable only if they did not contain any implementation code. Starting with Scala 2.12, all traits are interoperable with Java.
From Stack Overflow: asked by Ralf, answered by Mushtaq Ahmed (CC BY-SA 4.0)
Scala list concatenation, ::: vs ++
Legacy. List was originally defined to be functional-languages-looking:
1 :: 2 :: Nil // a list list1 ::: list2 // concatenation of two lists list match { case head :: tail => "non-empty" case Nil => "empty" }Of course, Scala evolved other collections, in an ad-hoc manner. When 2.8 came out, the collections were redesigned for maximum code reuse and consistent API, so that you can use
++to concatenate any two collections -- and even iterators. List, however, got to keep its original operators, aside from one or two which got deprecated.From Stack Overflow: asked by Luigi Plinge, answered by Daniel C. Sobral (CC BY-SA 3.0)
Difference between a Seq and a List in Scala
In Java terms, Scala's
Seqwould be Java'sList, and Scala'sListwould be Java'sLinkedList.Note that
Seqis atrait, which is similar to Java'sinterface, including the equivalent of default methods. Scala'sListis an abstract class that is extended byNiland::, which are the concrete implementations ofList.So, where Java's
Listis aninterface, Scala'sListis an implementation.Beyond that, Scala's
Listis immutable, which is not the case ofLinkedList. In fact, Java has no equivalent to immutable collections (the read only thing only guarantees the new object cannot be changed, but you still can change the old one, and, therefore, the "read only" one).Scala's
Listis highly optimized by compiler and libraries, and it's a fundamental data type in functional programming. However, it has limitations and it's inadequate for parallel programming. These days,Vectoris a better choice thanList, but habit is hard to break.Seqis a good generalization for sequences, so if you program to interfaces, you should use that. Note that there are actually three of them:collection.Seq,collection.mutable.Seqandcollection.immutable.Seq, and it is the latter one that is the "default" imported into scope.There's also
GenSeqandParSeq. The latter methods run in parallel where possible, while the former is parent to bothSeqandParSeq, being a suitable generalization for when there is no concern for code parallelism. They are both relatively new, so people don't use them as much.From Stack Overflow: asked by opensas, answered by Daniel C. Sobral (CC BY-SA 4.0)
What is a TypeTag and how do I use it?
A
TypeTagsolves the problem that Scala's types are erased at runtime (type erasure). If we wanna doclass Foo class Bar extends Foo def meth[A](xs: List[A]) = xs match { case _: List[String] => "list of strings" case _: List[Foo] => "list of foos" }we will get warnings:
<console>:23: warning: non-variable type argument String in type pattern List[String]↩ is unchecked since it is eliminated by erasure case _: List[String] => "list of strings" ^ <console>:24: warning: non-variable type argument Foo in type pattern List[Foo]↩ is unchecked since it is eliminated by erasure case _: List[Foo] => "list of foos" ^To solve this problem Manifests were introduced to Scala. But they have the problem not being able to represent a lot of useful types, like path-dependent-types:
scala> class Foo{class Bar} defined class Foo scala> def m(f: Foo)(b: f.Bar)(implicit ev: Manifest[f.Bar]) = ev warning: there were 2 deprecation warnings; re-run with -deprecation for details m: (f: Foo)(b: f.Bar)(implicit ev: Manifest[f.Bar])Manifest[f.Bar] scala> val f1 = new Foo;val b1 = new f1.Bar f1: Foo = Foo@681e731c b1: f1.Bar = Foo$Bar@271768ab scala> val f2 = new Foo;val b2 = new f2.Bar f2: Foo = Foo@3e50039c b2: f2.Bar = Foo$Bar@771d16b9 scala> val ev1 = m(f1)(b1) warning: there were 2 deprecation warnings; re-run with -deprecation for details ev1: Manifest[f1.Bar] = Foo@681e731c.type#Foo$Bar scala> val ev2 = m(f2)(b2) warning: there were 2 deprecation warnings; re-run with -deprecation for details ev2: Manifest[f2.Bar] = Foo@3e50039c.type#Foo$Bar scala> ev1 == ev2 // they should be different, thus the result is wrong res28: Boolean = trueThus, they are replaced by TypeTags, which are both much simpler to use and well integrated into the new Reflection API. With them we can solve the problem above about path-dependent-types elegantly:
scala> def m(f: Foo)(b: f.Bar)(implicit ev: TypeTag[f.Bar]) = ev m: (f: Foo)(b: f.Bar)(implicit ev: reflect.runtime.universe.TypeTag[f.Bar])↩ reflect.runtime.universe.TypeTag[f.Bar] scala> val ev1 = m(f1)(b1) ev1: reflect.runtime.universe.TypeTag[f1.Bar] = TypeTag[f1.Bar] scala> val ev2 = m(f2)(b2) ev2: reflect.runtime.universe.TypeTag[f2.Bar] = TypeTag[f2.Bar] scala> ev1 == ev2 // the result is correct, the type tags are different res30: Boolean = false scala> ev1.tpe =:= ev2.tpe // this result is correct, too res31: Boolean = falseThey are also easy to use to check type parameters:
import scala.reflect.runtime.universe._ def meth[A : TypeTag](xs: List[A]) = typeOf[A] match { case t if t =:= typeOf[String] => "list of strings" case t if t <:< typeOf[Foo] => "list of foos" } scala> meth(List("string")) res67: String = list of strings scala> meth(List(new Bar)) res68: String = list of foosAt this point, it is extremely important to understand to use
=:=(type equality) and<:<(subtype relation) for equality checks. Do never use==or!=, unless you absolutely know what you do:scala> typeOf[List[java.lang.String]] =:= typeOf[List[Predef.String]] res71: Boolean = true scala> typeOf[List[java.lang.String]] == typeOf[List[Predef.String]] res72: Boolean = falseThe latter checks for structural equality, which often is not what should be done because it doesn't care about things such as prefixes (like in the example).
A
TypeTagis completely compiler-generated, that means that the compiler creates and fills in aTypeTagwhen one calls a method expecting such aTypeTag. There exist three different forms of tags:Read the rest at the sourceFrom Stack Overflow: asked by Sergey Weiss, answered by kiritsuku (CC BY-SA 3.0)
What is a sealed trait?
A
sealedtrait can be extended only in the same file as its declaration.They are often used to provide an alternative to
enums. Since they can be only extended in a single file, the compiler knows every possible subtypes and can reason about it.For instance with the declaration:
sealed trait Answer case object Yes extends Answer case object No extends AnswerThe compiler will emit a warning if a match is not exhaustive:
scala> val x: Answer = Yes x: Answer = Yes scala> x match { | case No => println("No") | } <console>:12: warning: match is not exhaustive! missing combination YesSo you should use sealed traits (or sealed abstract class) if the number of possible subtypes is finite and known in advance. For more examples you can have a look at list and option implementations.
From Stack Overflow: asked by John Threepwood, answered by paradigmatic (CC BY-SA 3.0)
What is the formal difference in Scala between braces and parentheses, and when should they be used?
I tried once to write about this, but I gave up in the end, as the rules are somewhat diffuse. Basically, you’ll have to get the hang of it.
Perhaps it is best to concentrate on where curly braces and parentheses can be used interchangeably: when passing parameters to method calls. You may replace curly braces with parentheses if, and only if, the method expects a single parameter. For example:
List(1, 2, 3).reduceLeft{_ + _} // valid, single Function2[Int,Int] parameter List{1, 2, 3}.reduceLeft(_ + _) // invalid, A* vararg parameterHowever, there’s more you need to know to better grasp these rules.
Increased compile checking with parens
The authors of Spray recommend round parens because they give increased compile checking. This is especially important for DSLs like Spray. By using parens you are telling the compiler that it should only be given a single line; therefore if you accidentally give it two or more, it will complain. Now this isn’t the case with curly braces – if for example you forget an operator somewhere, then your code will compile, and you get unexpected results and potentially a very hard bug to find. Below is contrived (since the expressions are pure and will at least give a warning), but makes the point:
method { 1 + 2 3 } method( 1 + 2 3 )The first compiles, the second gives
error: ')' expected but integer literal found. The author wanted to write1 + 2 + 3.One could argue it’s similar for multi-parameter methods with default arguments; it’s impossible to accidentally forget a comma to separate parameters when using parens.
Verbosity
An important often overlooked note about verbosity. Using curly braces inevitably leads to verbose code since the Scala style guide clearly states that closing curly braces must be on their own line:
… the closing brace is on its own line immediately following the last line of the function.
Many auto-reformatters, like in IntelliJ, will automatically perform this reformatting for you. So try to stick to using round parens when you can.
Infix Notation
When using infix notation, like
List(1,2,3) indexOf (2)you can omit parentheses if there is only one parameter and write it asList(1, 2, 3) indexOf 2. This is not the case of dot-notation.Note also that when you have a single parameter that is a multi-token expression, like
x + 2ora => a % 2 == 0, you have to use parentheses to indicate the boundaries of the expression.Tuples
Because you can omit parentheses sometimes, sometimes a tuple needs extra parentheses like in
((1, 2)), and sometimes the outer parentheses can be omitted, like in(1, 2). This may cause confusion.Function/Partial Function literals with
caseScala has a syntax for function and partial function literals. It looks like this:
{ case pattern if guard => statements case pattern => statements }The only other places where you can use
casestatements are with thematchandcatchkeywords:object match { case pattern if guard => statements case pattern => statements }try { block } catch { case pattern if guard => statements case pattern => statements } finally { block }You cannot use
casestatements in any other context. So, if you want to usecase, you need curly braces. In case you are wondering what makes the distinction between a function and partial function literal, the answer is: context. If Scala expects a function, a function you get. If it expects a partial function, you get a partial function. If both are expected, it gives an error about ambiguity.Expressions and Blocks
Read the rest at the sourceFrom Stack Overflow: asked by Jean-Philippe Pellet, answered by Daniel C. Sobral (CC BY-SA 4.0)
What is the apply function in Scala?
Mathematicians have their own little funny ways, so instead of saying "then we call function
fpassing itxas a parameter" as we programmers would say, they talk about "applying functionfto its argumentx".In mathematics and computer science, Apply is a function that applies functions to arguments.
Wikipediaapplyserves the purpose of closing the gap between Object-Oriented and Functional paradigms in Scala. Every function in Scala can be represented as an object. Every function also has an OO type: for instance, a function that takes anIntparameter and returns anIntwill have OO type ofFunction1[Int,Int].// define a function in scala (x:Int) => x + 1 // assign an object representing the function to a variable val f = (x:Int) => x + 1Since everything is an object in Scala
fcan now be treated as a reference toFunction1[Int,Int]object. For example, we can calltoStringmethod inherited fromAny, that would have been impossible for a pure function, because functions don't have methods:f.toStringOr we could define another
Function1[Int,Int]object by callingcomposemethod onfand chaining two different functions together:val f2 = f.compose((x:Int) => x - 1)Now if we want to actually execute the function, or as mathematician say "apply a function to its arguments" we would call the
applymethod on theFunction1[Int,Int]object:f2.apply(2)Writing
f.apply(args)every time you want to execute a function represented as an object is the Object-Oriented way, but would add a lot of clutter to the code without adding much additional information and it would be nice to be able to use more standard notation, such asf(args). That's where Scala compiler steps in and whenever we have a referencefto a function object and writef (args)to apply arguments to the represented function the compiler silently expandsf (args)to the object method callf.apply (args).Every function in Scala can be treated as an object and it works the other way too - every object can be treated as a function, provided it has the
applymethod. Such objects can be used in the function notation:// we will be able to use this object as a function, as well as an object object Foo { var y = 5 def apply (x: Int) = x + y } Foo (1) // using Foo object in function notationThere are many usage cases when we would want to treat an object as a function. The most common scenario is a factory pattern. Instead of adding clutter to the code using a factory method we can
applyobject to a set of arguments to create a new instance of an associated class:List(1,2,3) // same as List.apply(1,2,3) but less clutter, functional notation // the way the factory method invocation would have looked // in other languages with OO notation - needless clutter List.instanceOf(1,2,3)So
applymethod is just a handy way of closing the gap between functions and objects in Scala.From Stack Overflow: asked by Jesvin Jose, answered by Vlad Gudim (CC BY-SA 3.0)
What does "coalgebra" mean in the context of programming?
Algebras
I think the place to start would be to understand the idea of an algebra. This is just a generalization of algebraic structures like groups, rings, monoids and so on. Most of the time, these things are introduced in terms of sets, but since we're among friends, I'll talk about Haskell types instead. (I can't resist using some Greek letters though—they make everything look cooler!)
An algebra, then, is just a type
τwith some functions and identities. These functions take differing numbers of arguments of typeτand produce aτ: uncurried, they all look like(τ, τ,…, τ) → τ. They can also have "identities"—elements ofτthat have special behavior with some of the functions.The simplest example of this is the monoid. A monoid is any type
τwith a functionmappend ∷ (τ, τ) → τand an identitymzero ∷ τ. Other examples include things like groups (which are just like monoids except with an extrainvert ∷ τ → τfunction), rings, lattices and so on.All the functions operate on
τbut can have different arities. We can write these out asτⁿ → τ, whereτⁿmaps to a tuple ofnτ. This way, it makes sense to think of identities asτ⁰ → τwhereτ⁰is just the empty tuple(). So we can actually simplify the idea of an algebra now: it's just some type with some number of functions on it.An algebra is just a common pattern in mathematics that's been "factored out", just like we do with code. People noticed that a whole bunch of interesting things—the aforementioned monoids, groups, lattices and so on—all follow a similar pattern, so they abstracted it out. The advantage of doing this is the same as in programming: it creates reusable proofs and makes certain kinds of reasoning easier.
F-Algebras
However, we're not quite done with factoring. So far, we have a bunch of functions
τⁿ → τ. We can actually do a neat trick to combine them all into one function. In particular, let's look at monoids: we havemappend ∷ (τ, τ) → τandmempty ∷ () → τ. We can turn these into a single function using a sum type—Either. It would look like this:op ∷ Monoid τ ⇒ Either (τ, τ) () → τ op (Left (a, b)) = mappend (a, b) op (Right ()) = memptyWe can actually use this transformation repeatedly to combine all the
τⁿ → τfunctions into a single one, for any algebra. (In fact, we can do this for any number of functionsa → τ,b → τand so on for anya, b,….)This lets us talk about algebras as a type
τwith a single function from some mess ofEithers to a singleτ. For monoids, this mess is:Either (τ, τ) (); for groups (which have an extraτ → τoperation), it's:Either (Either (τ, τ) τ) (). It's a different type for every different structure. So what do all these types have in common? The most obvious thing is that they are all just sums of products—algebraic data types. For example, for monoids, we could create a monoid argument type that works for any monoid τ:data MonoidArgument τ = Mappend τ τ -- here τ τ is the same as (τ, τ) | Mempty -- here we can just leave the () outWe can do the same thing for groups and rings and lattices and all the other possible structures.
What else is special about all these types? Well, they're all
Functors! E.g.:instance Functor MonoidArgument where fmap f (Mappend τ τ) = Mappend (f τ) (f τ) fmap f Mempty = MemptySo we can generalize our idea of an algebra even more. It's just some type
τwith a functionf τ → τfor some functorf. In fact, we could write this out as a typeclass:class Functor f ⇒ Algebra f τ where op ∷ f τ → τThis is often called an "F-algebra" because it's determined by the functor
F. If we could partially apply typeclasses, we could define something likeclass Monoid = Algebra MonoidArgument.Read the rest at the sourceFrom Stack Overflow: asked by missingfaktor, answered by Tikhon Jelvis (CC BY-SA 3.0)
Understanding implicit in Scala
I'll explain the main use cases of implicits below, but for more detail see the relevant chapter of Programming in Scala.
Implicit parameters
The final parameter list on a method can be marked
implicit, which means the values will be taken from the context in which they are called. If there is no implicit value of the right type in scope, it will not compile. Since the implicit value must resolve to a single value and to avoid clashes, it's a good idea to make the type specific to its purpose, e.g. don't require your methods to find an implicitInt!example:
// probably in a library class Prefixer(val prefix: String) def addPrefix(s: String)(implicit p: Prefixer) = p.prefix + s // then probably in your application implicit val myImplicitPrefixer = new Prefixer("***") addPrefix("abc") // returns "***abc"Implicit conversions
When the compiler finds an expression of the wrong type for the context, it will look for an implicit
Functionvalue of a type that will allow it to typecheck. So if anAis required and it finds aB, it will look for an implicit value of typeB => Ain scope (it also checks some other places like in theBandAcompanion objects, if they exist). Sincedefs can be "eta-expanded" intoFunctionobjects, animplicit def xyz(arg: B): Awill do as well.So the difference between your methods is that the one marked
implicitwill be inserted for you by the compiler when aDoubleis found but anIntis required.implicit def doubleToInt(d: Double) = d.toInt val x: Int = 42.0will work the same as
def doubleToInt(d: Double) = d.toInt val x: Int = doubleToInt(42.0)In the second we've inserted the conversion manually; in the first the compiler did the same automatically. The conversion is required because of the type annotation on the left hand side.
Regarding your first snippet from Play:
Actions are explained on this page from the Play documentation (see also API docs). You are using
apply(block: (Request[AnyContent]) ⇒ Result): Action[AnyContent]on the
Actionobject (which is the companion to the trait of the same name).So we need to supply a Function as the argument, which can be written as a literal in the form
request => ...In a function literal, the part before the
=>is a value declaration, and can be markedimplicitif you want, just like in any othervaldeclaration. Here,requestdoesn't have to be markedimplicitfor this to type check, but by doing so it will be available as an implicit value for any methods that might need it within the function (and of course, it can be used explicitly as well). In this particular case, this has been done because thebindFromRequestmethod on the Form class requires an implicitRequestargument.From Stack Overflow: asked by Clive, answered by Luigi Plinge (CC BY-SA 3.0)
What is Scala's yield?
I think the accepted answer is great, but it seems many people have failed to grasp some fundamental points.
First, Scala's
forcomprehensions are equivalent to Haskell'sdonotation, and it is nothing more than a syntactic sugar for composition of multiple monadic operations. As this statement will most likely not help anyone who needs help, let's try again… :-)Scala's
forcomprehensions is syntactic sugar for composition of multiple operations with map,flatMapandfilter. Orforeach. Scala actually translates afor-expression into calls to those methods, so any class providing them, or a subset of them, can be used with for comprehensions.First, let's talk about the translations. There are very simple rules:
This
for(x <- c1; y <- c2; z <-c3) {...}is translated into
c1.foreach(x => c2.foreach(y => c3.foreach(z => {...})))This
for(x <- c1; y <- c2; z <- c3) yield {...}is translated into
c1.flatMap(x => c2.flatMap(y => c3.map(z => {...})))This
for(x <- c; if cond) yield {...}is translated on Scala 2.7 into
c.filter(x => cond).map(x => {...})or, on Scala 2.8, into
c.withFilter(x => cond).map(x => {...})with a fallback into the former if method
withFilteris not available butfilteris. Please see the section below for more information on this.This
for(x <- c; y = ...) yield {...}is translated into
c.map(x => (x, ...)).map((x,y) => {...})
When you look at very simple
forcomprehensions, themap/foreachalternatives look, indeed, better. Once you start composing them, though, you can easily get lost in parenthesis and nesting levels. When that happens,forcomprehensions are usually much clearer.I'll show one simple example, and intentionally omit any explanation. You can decide which syntax was easier to understand.
l.flatMap(sl => sl.filter(el => el > 0).map(el => el.toString.length))or
for { sl <- l el <- sl if el > 0 } yield el.toString.lengthwithFilterScala 2.8 introduced a method called
withFilter, whose main difference is that, instead of returning a new, filtered, collection, it filters on-demand. Thefiltermethod has its behavior defined based on the strictness of the collection. To understand this better, let's take a look at some Scala 2.7 withList(strict) andStream(non-strict):scala> var found = false found: Boolean = false scala> List.range(1,10).filter(_ % 2 == 1 && !found).foreach(x => if (x == 5) found = true else println(x)) 1 3 7 9 scala> found = false found: Boolean = false scala> Stream.range(1,10).filter(_ % 2 == 1 && !found).foreach(x => if (x == 5) found = true else println(x)) 1 3The difference happens because
filteris immediately applied withList, returning a list of odds -- sincefoundisfalse. Only thenforeachis executed, but, by this time, changingfoundis meaningless, asfilterhas already executed.In the case of
Stream, the condition is not immediatelly applied. Instead, as each element is requested byforeach,filtertests the condition, which enablesforeachto influence it throughfound. Just to make it clear, here is the equivalent for-comprehension code:for (x <- List.range(1, 10); if x % 2 == 1 && !found) if (x == 5) found = true else println(x) for (x <- Stream.range(1, 10); if x % 2 == 1 && !found) if (x == 5) found = true else println(x)Read the rest at the sourceFrom Stack Overflow: asked by Geo, answered by Daniel C. Sobral (CC BY-SA 4.0)
What is the difference between a var and val definition in Scala?
As so many others have said, the object assigned to a
valcannot be replaced, and the object assigned to avarcan. However, said object can have its internal state modified. For example:class A(n: Int) { var value = n } class B(n: Int) { val value = new A(n) } object Test { def main(args: Array[String]) { val x = new B(5) x = new B(6) // Doesn't work, because I can't replace the object created on the line above with this new one. x.value = new A(6) // Doesn't work, because I can't replace the object assigned to B.value for a new one. x.value.value = 6 // Works, because A.value can receive a new object. } }So, even though we can't change the object assigned to
x, we could change the state of that object. At the root of it, however, there was avar.Now, immutability is a good thing for many reasons. First, if an object doesn't change internal state, you don't have to worry if some other part of your code is changing it. For example:
x = new B(0) f(x) if (x.value.value == 0) println("f didn't do anything to x") else println("f did something to x")This becomes particularly important with multithreaded systems. In a multithreaded system, the following can happen:
x = new B(1) f(x) if (x.value.value == 1) { print(x.value.value) // Can be different than 1! }If you use
valexclusively, and only use immutable data structures (that is, avoid arrays, everything inscala.collection.mutable, etc.), you can rest assured this won't happen. That is, unless there's some code, perhaps even a framework, doing reflection tricks -- reflection can change "immutable" values, unfortunately.That's one reason, but there is another reason for it. When you use
var, you can be tempted into reusing the samevarfor multiple purposes. This has some problems:- It will be more difficult for people reading the code to know what is the value of a variable in a certain part of the code.
- You may forget to re-initialize the variable in some code path, and end up passing wrong values downstream in the code.
Simply put, using
valis safer and leads to more readable code.We can, then, go the other direction. If
valis that better, why havevarat all? Well, some languages did take that route, but there are situations in which mutability improves performance, a lot.For example, take an immutable
Queue. When you eitherenqueueordequeuethings in it, you get a newQueueobject. How then, would you go about processing all items in it?I'll go through that with an example. Let's say you have a queue of digits, and you want to compose a number out of them. For example, if I have a queue with 2, 1, 3, in that order, I want to get back the number 213. Let's first solve it with a
mutable.Queue:def toNum(q: scala.collection.mutable.Queue[Int]) = { var num = 0 while (!q.isEmpty) { num *= 10 num += q.dequeue } num }This code is fast and easy to understand. Its main drawback is that the queue that is passed is modified by
toNum, so you have to make a copy of it beforehand. That's the kind of object management that immutability makes you free from.Now, let's covert it to an
immutable.Queue:def toNum(q: scala.collection.immutable.Queue[Int]) = { def recurse(qr: scala.collection.immutable.Queue[Int], num: Int): Int = { if (qr.isEmpty) num else { val (digit, newQ) = qr.dequeue recurse(newQ, num * 10 + digit) } } recurse(q, 0) }Because I can't reuse some variable to keep track of my
num, like in the previous example, I need to resort to recursion. In this case, it is a tail-recursion, which has pretty good performance. But that is not always the case: sometimes there is just no good (readable, simple) tail recursion solution.Note, however, that I can rewrite that code to use an
immutable.Queueand avarat the same time! For example:Read the rest at the sourceFrom Stack Overflow: asked by Derek Mahar, answered by Daniel C. Sobral (CC BY-SA 3.0)
Read entire file in Scala?
val lines = scala.io.Source.fromFile("file.txt").mkStringBy the way, "
scala." isn't really necessary, as it's always in scope anyway, and you can, of course, import io's contents, fully or partially, and avoid having to prepend "io." too.The above leaves the file open, however. To avoid problems, you should close it like this:
val source = scala.io.Source.fromFile("file.txt") val lines = try source.mkString finally source.close()Another problem with the code above is that it is horribly slow due to its implementation. For larger files one should use:
source.getLines mkString "\n"From Stack Overflow: asked by Brendan OConnor, answered by Daniel C. Sobral (CC BY-SA 4.0)
How to show full column content in a Spark Dataframe?
results.show(20, false)will not truncate, note that Python would requireFalserather thanfalsewhich is valid in Scala/Java/Spark shell.Check the source
20is the default number of rows displayed whenshow()is called without any arguments.From Stack Overflow: asked by tracer, answered by TomTom101 (CC BY-SA 4.0)
How to use java.String.format in Scala?
While all the previous responses are correct, they're all in Java. Here's a Scala example:
val placeholder = "Hello %s, isn't %s cool?" val formatted = placeholder.format("Ivan", "Scala")I also have a blog post about making
formatlike Python's%operator that might be useful.From Stack Overflow: asked by Ivan, answered by pr1001 (CC BY-SA 4.0)
How do I break out of a loop in Scala?
You have three (or so) options to break out of loops.
Suppose you want to sum numbers until the total is greater than 1000. You try
var sum = 0 for (i <- 0 to 1000) sum += iexcept you want to stop when (sum > 1000).
What to do? There are several options.
(1a) Use some construct that includes a conditional that you test.
var sum = 0 (0 to 1000).iterator.takeWhile(_ => sum < 1000).foreach(i => sum+=i)(warning--this depends on details of how the takeWhile test and the foreach are interleaved during evaluation, and probably shouldn't be used in practice!).
(1b) Use tail recursion instead of a for loop, taking advantage of how easy it is to write a new method in Scala:
var sum = 0 def addTo(i: Int, max: Int) { sum += i; if (sum < max) addTo(i+1,max) } addTo(0,1000)(1c) Fall back to using a while loop
var sum = 0 var i = 0 while (i <= 1000 && sum <= 1000) { sum += i; i += 1 }(2) In Scala 3.3+, use boundaries instead (for more info):
import scala.util.boundary, boundary.break boundary { for i <- 0 to 1000 do sum += i if sum >= 1000 then break() }(3) Throw an exception.
object AllDone extends Exception { } var sum = 0 try { for (i <- 0 to 1000) { sum += i; if (sum>=1000) throw AllDone } } catch { case AllDone => }(3a) In Scala 2.8+ this is already pre-packaged in
scala.util.control.Breaksusing syntax that looks a lot like your familiar old break from C/Java:import scala.util.control.Breaks._ var sum = 0 breakable { for (i <- 0 to 1000) { sum += i if (sum >= 1000) break } }(4) Put the code into a method and use return.
var sum = 0 def findSum { for (i <- 0 to 1000) { sum += i; if (sum>=1000) return } } findSumThis is intentionally made not-too-easy for at least three reasons I can think of. First, in large code blocks, it's easy to overlook "continue" and "break" statements, or to think you're breaking out of more or less than you really are, or to need to break two loops which you can't do easily anyway--so the standard usage, while handy, has its problems, and thus you should try to structure your code a different way. Second, Scala has all sorts of nestings that you probably don't even notice, so if you could break out of things, you'd probably be surprised by where the code flow ended up (especially with closures). Third, most of Scala's "loops" aren't actually normal loops--they're method calls that have their own loop, or they are recursion which may or may not actually be a loop--and although they act looplike, it's hard to come up with a consistent way to know what "break" and the like should do. So, to be consistent, the wiser thing to do is not to have a "break" at all.
Note: There are functional equivalents of all of these where you return the value of
sumrather than mutate it in place. These are more idiomatic Scala. However, the logic remains the same. (returnbecomesreturn x, etc.).From Stack Overflow: asked by TiansHUo, answered by Rex Kerr (CC BY-SA 4.0)
More Scala questions, without answers
- What is the difference between a
var, avalanddef? - What is the difference between a
traitand anabstract class? - What is the difference between an
objectand aclass? - What is a
case class? - What is the difference between a Java future and a Scala future?
- What is the difference between
unapplyandapply, when would you use them? - What is a companion object?
- What is the difference between the following terms and types in Scala:
Nil,Null,None,Nothing? - What is
Unit? - What is the difference between a
call-by-valueandcall-by-nameparameter? - Define uses for the
Optionmonad and good practices it provides. - How does
yieldwork? - Explain the implicit parameter precedence.
- What operations is a
for comprehensionsyntactic sugar for? - What is a
functor? - What is a
applicative? - What is a
monad? - Explain higher order functions.
- What is gained from using immutable objects?
- What is tail recursion?
- What is function currying?
- What are implicit parameters?
- What are typeclasses?
- What are lenses?
- What is and which are the uses of: Enumerators, Enumeratees and Iteratee?
- Explain the actor model.
- What are benefits of non-blocking (asynchronous I/O) over blocking (synchronous I/O).
- Do you think that Scala has the same async spirit as Node.js?
- Explain the difference between
concurrencyandparallelism, and name some constructs you can use in Scala to leverage both. - What is the global ExecutionContext?
Related topics
Where these questions come from
Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.
- Scala Job Interview Questionsby the Scala-Interview-Questions contributorsMIT, © 2012 - 2015 Contributors to https://github.com/jarlakxen/Scala-Interview-Questions30 questions
- Stack Overflowby its contributors, named on each answerCC BY-SA24 questions