Snippets

scala

Access modifiers

Access modifiers can be augmented with qualifiers. A modifier of the form private[X] or protected[X] means that access is private or protected "up to" X, where X designates some enclosing package, class or singleton object.
package quizful {
   package prof {
      class Executive {
         private[prof] var details = null
         private[quizful] var friends = null
         private[this] var secrets = null

         def help(another : Executive) {
            println(another.details)
            println(another.secrets) //ERROR
         }
      }
   }
}
Note the following points:
  • Variable details will be accessible to any class within the enclosing package prof.
  • Variable friends will be accessible to any class within the enclosing package quizful.
  • Variable secrets will be accessible only on the implicit object within instance methods (this).

access modifiers qualifiers

scala

Import clauses

Import clauses
An import clause has the form import p.X where the import expression X determines a set of names of members of p which are made available without qualification.
import p._	// all members of p (this is analogous to import p.* in Java).
import p.x	// the member x of p.
import p.{x => a}	// the member x of p renamed as a.
import p.{x, y}	// the members x and y of p.
import p1.p2.z	// the member z of p2, itself member of p1.
 
Furthermore, the clause import p1._, p2._ is a shorthand for import p1._; import p2._. Implicitly imported into every compilation unit are, in that order:
  • the package java.lang,
  • the package scala,
  • and the object scala.Predef.
Members of a later import in that order hide members of an earlier import.

import

scala

Arity-1

Arity-1
Scala has a special syntax for invoking methods of arity-1 (one argument):
names.mkString(",")
// is the same as
names mkString ","
This syntax is formally known as “infix notation”. It should only be used for purely-functional methods (methods with no side-effects) - such as mkString -or methods which take functions as parameters - such as foreach:
// right!
names foreach (n => println(n))
names mkString ","
optStr getOrElse ""
// wrong!
javaList add item
Read more: Scala documentation: Method Invocation

infix notation arity-1

scala

Higher-order Functions

Higher-order Functions
Scala allows the definition of higher-order functions. These are functions that take other functions as parameters, or whose result is a function. Here is a function apply which takes another function f and a value v and applies function f to v:
def apply(f: Int => String, v: Int) = f(v)
Note: methods are automatically coerced to functions if the context requires this.
Read more: Scala documentation

scala

Higher-order Functions Example

Higher-order Functions
Here is another example of usage of higher-order functions:
class Decorator(left: String, right: String) {
  def layout[A](x: A) = left + x.toString() + right
}
object QuizfulTest extends App {
  def apply(f: Int => String, v: Int) = f(v)
  val decorator = new Decorator("[", "]")
  println(apply(decorator.layout, 2015))
}
Execution yields the output:
[2015]
In this example, the method decorator.layout is coerced automatically to a value of type Int => String as required by method apply. Please note that method decorator.layout is a polymorphic method (i.e. it abstracts over some of its signature types) and the Scala compiler has to instantiate its method type first appropriately.
Read more: Scala documentation

higher-order functions polymorphic method

scala

Unit

Unit is a subtype of scala.AnyVal. There is only one value of type Unit, (), and it is not represented by any object in the underlying runtime system. A method with return type Unit is analogous to a Java method which is declared void.

return type

scala

Unit Example

Unit
Here’s an example:
scala> def doTwoTimes(fn: (Int) => Unit) = {
     |   fn(1); fn(2); 
     | }
doThreeTimes: ((Int) => Unit)Unit
 
scala> doTwoTimes(println)
1
2
 
scala> def specialPrint(num: Int) = {
     |    println(">>>" + num + "<<<")
     | }
specialPrint: (Int)Unit
 
scala> doTwoTimes(specialPrint)
>>>1<<<
>>>2<<<
>>>3<<<
In the definition of doTwoTimes we specify that the method takes a parameter called fn, which has a type of (Int) => Unit. This means that fn is a method that takes a single parameter of type Int and a return type of Unit, which is to say fn isn’t supposed to return a value at all just like a Java void function.

unit void

scala

Sealed Classes

Sealed Classes A sealed class may not be directly inherited, except if the inheriting template is defined in the same source file as the inherited class. However, subclasses of a sealed class can inherited anywhere.
Sealed classes are defined using the sealed modifier.
Read more: A Tour of Scala: Sealed Classes

sealed class

scala

Pattern Matching of Sealed Classes

Sealed Classes
If the selector of a pattern match is an instance of a sealed class, the compilation of pattern matching can emit warnings which diagnose that a given set of patterns is not exhaustive, i.e. that there is a possibility of a MatchError being raised at run-time.
When applied to the selector of a match expression, the @unchecked annotation suppresses any warnings about non-exhaustive pattern matches which would otherwise be emitted. For instance, no warnings would be produced for the method definition below.
def f(x: Option[Int]) = (x: @unchecked) match {
  case Some(y) => y
}
Without the @unchecked annotation, a Scala compiler could infer that the pattern match is non-exhaustive, and could produce awarning because Option is a sealed class.
Read more: A Tour of Scala: Sealed Classes

match expression pattern matching

scala

Partially applied function

A partially applied function is an expression in which you don't supply all of the arguments needed by the function. Instead, you supply some, or none, of the needed arguments. For example, to create a partially applied function expression involving sum,
scala> def sum(a: Int, b: Int, c: Int) = a + b + c
sum: (a: Int,b: Int,c: Int)Int
in which you supply none of the three required arguments, you just place an underscore after "sum". The resulting function can then be stored in a variable. Here's an example:
scala> val a = sum _
a: (Int, Int, Int) => Int = 
Read more: Partially applied functions

functions partially applied functions

Loading rules...