What does the `#` operator mean in Scala? link Nested classes in scala are instance specific. To treat them at class level we access them with #:

To explain it, we first have to explain nested classes in Scala. Consider this simple example:

class A {
  class B

  def f(b: B) = println("Got my B!")

Now let's try something with it:

scala> val a1 = new A
a1: A = A@2fa8ecf4

scala> val a2 = new A
a2: A = A@4bed4c8

scala> a2.f(new a1.B)
<console>:11: error: type mismatch;
 found   : a1.B
 required: a2.B
              a2.f(new a1.B)

When you declare a class inside another class in Scala, you are saying that each instance of that class has such a subclass. In other words, there's no A.B class, but there are a1.B and a2.B classes, and they are different classes, as the error message is telling us above.

If you did not understand that, look up path dependent types.

Now, # makes it possible for you to refer to such nested classes without restricting it to a particular instance. In other words, there's no A.B, but there's A#B, which means a B nested class of any instance of A.

We can see this in work by changing the code above:

class A {
  class B

  def f(b: B) = println("Got my B!")
  def g(b: A#B) = println("Got a B.")

And trying it out:

scala> val a1 = new A
a1: A = A@1497b7b1

scala> val a2 = new A
a2: A = A@2607c28c

scala> a2.f(new a1.B)
<console>:11: error: type mismatch;
 found   : a1.B
 required: a2.B
              a2.f(new a1.B)

scala> a2.g(new a1.B)
Got a B.

if you define a trait it is like having an interface which defines its methods and can be in a multiple inheritance manner

Similar to interfaces in Java, traits are used to define object types by specifying the signature of the supported methods. Unlike Java, Scala allows traits to be partially implemented; i.e. it is possible to define default implementations for some methods. In contrast to classes, traits may not have constructor parameters.

abstract class Bird {
    def flyMessage: String
    def fly() = println(flyMessage)

trait Flying { def flyMessage: String def fly() = println(flyMessage) }

trait Swimming { def swim() = println("I'm swimming") }

class Pigeon extends Bird with Swimming with Flying { val flyMessage = "I'm a good flyer" }

Mixing in traits upon instantiation
val pigeon = new Pigeon with Swimming

 yes, Serializable is an interface. but you use 'extends' for the first trait or the parent class, and 'with' only for additional traits

Java Heap size memory:
expoer JAVA_OPTS="-Xmx1024m -Xms256m"
 -Xms<size> set initial Java heap size
-Xmx<size>        set maximum Java heap size
-Xss<size>        set java thread stack size

 Scala IDE  info      Programming Scala - O'Rielly           Scala API Doc

FREE ebook on scala: Programming in Scala     On sbt, scala and scalaTest    Quick start Scala/MongoDB  

$ git pull
$ sbt eclipse
$ git add ./abc/file.txt
$ git commit -m "commit message"
$ git push

A multi-line string literal is a sequence of characters enclosed in triple quotes """ ... """. The null value is of type scala.Null, and is thus compatible with every reference type. It denotes a reference value which refers to a special "null" object.
Define Variables
var myVar : String = "Foo"  //variable
val myVal : String = "Foo"   //immutable - constant

Scala supports multiple assignment. If a code block or method returns a Tuple, the Tuple can be assigned to a val variable.
val (myVar1: Int, myVar2: String) = Pair(40, "Foo")

If you have a reference to the object from outside the method. Method parameters are always mutable and defined by val keyword.

Access Modifier

private:  Java would permit both accesses because it lets an outer class access private members of its inner classes.
protected: only accessible from subclasses of the class in which the member is defined.

Modify access scope
package society {
   package professional {
      class Executive {
         private[professional] var workDetails = null
         private[society] var friends = null
         private[this] var secrets = null

         def help(another : Executive) {
            println(another.secrets) //ERROR

Variable workDetails will be accessible to any class within the enclosing package professional.
Variable friends will be accessible to any class within the enclosing package society.
Variable secrets will be accessible only on the implicit object within instance methods (this).


// nested for loop
 for( a <- 1 to 3; b <- 1 to 3){
   print( "Value of a: " + a );
   println( "Value of b: " + b );
 Value of a: 1Value of b: 1
Value of a: 1Value of b: 2
Value of a: 1Value of b: 3
Value of a: 2Value of b: 1
Value of a: 2Value of b: 2

// for loop execution with a collection (with multiple filters)
var a = 0;
val numList = List(1,2,3,4,5,6,7,8,9,10);

// for loop execution
for(    a <- numList
         if a != 3; if a < 8     ){
               println( "Value of a: " + a );

Yield (Get index range)
var a = 0;
val numList = List(1,2,3,4,5,6,7,8,9,10);

// for loop execution with a yield
var retVal = for{ a <- numList
                if a != 3; if a < 8
              }yield a      //for loop with no body and a yield

// Now print returned values using another loop.
for( a <- retVal){
 println( "Value of a: " + a );


Scala function's name can have characters like +, ++, ~, &,-, -- , \, /, : etc.
Parameter call by name parameter
a call-by-name parameter by putting the => symbol between the variable name and the type
object Test {
   def main(args: Array[String]) {
        delayed(time());      //  first goes to the delayed method and it won't evaluate parameter ntil it is required
   }                                //unlike java where parameters have early evaluation.

   def time() = {
      println("Getting time in nano seconds")
   def delayed( t: => Long ) = {
      println("In delayed method")
      println("Param: " + t)

In delayed method
Getting time in nano seconds
Param: 105771974498462
Getting time in nano seconds

last parameter to a function may be repeated. This allows clients to pass variable length argument lists to the function.

Currying function

Currying transforms a function that takes multiple parameters into a chain of functions, each taking a single parameter. Curried functions are defined with multiple parameter lists, as follows:
def strcat(s1: String)(s2: String) = s1 + s2
Alternatively, you can also use the following syntax to define a curried function:
def strcat(s1: String) = (s2: String) => s1 + s2Following is the syntax to call a curried function: strcat("foo")("bar")

Lists, Streams: Seq

val people : Array[Person]
val (minors, adults) people partition (_.age < 18)

val (minors, adults) people.par partition (_.age < 18)  //to do the samething in parallel


getOrElse(default)         access a value or a default when no value is present:


scala> Stream.cons(1, Stream.cons(2, Stream.empty))   ===   cons(1, cons(2, empty))    ====     1 #:: 2 #:: empty    //st1: Stream.Cons[Int] = Stream(1, ?)    //1, 2

scala> def numsFrom (n :Int):Stream[Int]  = Stream.cons(n,numsFrom (n+1))          //kinda w/ same meaning as Stream.cons.apply
scala> numsFrom(0) 
scala> n take 10 print                              // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, empty

scala> def numsFrom(start: Int): Stream[Int] = start #:: numsFrom(start + 1)
scala> println(f.take(10).mkString(","))        // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, empty

Remove items from Stream
f.drop(5)    //remove first n items and return a new stream.
Filter on Streams
scala> val even = f filter (_ % 2 == 0)    
scala> even take 10 print                          // 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, empty
// Now the first 19 elements of the natural number’s Stream has been initialized:
scala> println(f)          //Stream(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, ?)

Pattern Matching on Streams
scala> f match{case 0 #:: 1 #:: _ => println("matched")}         
 //matched  if the stream starts with 0,1. The trailing _underscore_ says that we are not interested in the remaining elements. 
Infinite Stream in Exception        
scala> f.sum
OpenJDK Server VM warning: Exception java.lang.OutOfMemoryError occurred dispatching signal SIGINT to handler- the VM may need to be forcibly terminated

A Stream can be used like every other collection because it is of type LinearSeq. Operations like filter and map are lazy evalutated. They simply return another Stream and perform the operation when required. I think we can say that all operations that return another Stream can be considered as lazy operations (like filter, map). Of course, operations like foldLeft, foldRight, find and exists are not lazy.

Stream is the immutable equivalent to Iterator.
While an Iterator doesn’t keep computated values Stream does. So as with any immutable data structure you don’t have to care about state with Streams. This is useful when you pass a Stream around to other functions. If you do so with a Iterator you have to care about state what needs much more caution and can lead to logic errors. The immutability of Streams makes it also quite easy to compose them. Keep in mind that a Stream has a higher memory footprint than an Iterator because it keeps the computed elements.


The only mutable collection. Scala has maps and sets that are mutable but should be used if there are performance issues with immutable maps/sets.
var z:Array[String] = new Array[String](3)          OR  var z = new Array[String](3)   //an array that can hold up to 3 elements
z(0) = "Zara"; z(1) = "Nuha"; z(4/2) = "Ayan"       OR var z = Array("Zara", "Nuha", "Ayan")

Multi-dimentional Array

var myMatrix = ofDim[Int](3,3) //an array with three elements each of which is an array with three elements
for (i <- 0 to 2) {
  for ( j <- 0 to 2) {
      myMatrix(i)(j) = j;
var myList1 = Array(1.9, 2.9, 3.4, 3.5)      
var myList2 = Array(8.9, 7.9, 0.4, 1.5)       

var myList3 =  concat( myList1, myList2)

var myList1 = range(10, 20, 2)  //from 10 to 20 step is 2


Linked list, elements are not repalceable like arrays (immutable)

val a: List[String] = List("apples", "oranges", "pears")  // List of Strings
val a: List[Nothing] = List()  // Empty List.
val a: List = List.fill(3)("apples") // Repeats apples three times.
ls.foreach( e => println(e.toUpperCase) )
val a: List[List[Int]] =   List( List(1, 0, 0),  List(0, 1, 0), List(0, 0, 1))  // Two dimensional list

val a = List(1,2,3)
val b = List(4,5,6)
      a ::: b                //   List(1, 2, 3, 4, 5, 6)
OR a.:::(b)               //   List(9, 5, 7, 1, 2, 3)      use two lists with Set.:::() method  
OR List.concat(a, b) 
OR a ++ b

 ! val a = List(1,2,3); val b = 0 :: a
  a: List[Int] = List(1, 2, 3)
  b: List[Int] = List(0, 1, 2, 3)
 ! (System.identityHashCode(a), System.identityHashCode(b.tail))
 (Int, Int) = (4434504,4434504)
 the tail of b *IS* a … no copying

Other Methods
def apply(n: Int): A      // Selects an element by its index in the list. Note: may take time die to the index value.
def map[B](f: (A) => B): List[B] // Builds a new collection by applying a function to all elements of this list.
def dropRight(n: Int): List[A]         //Returns all elements except last n ones.
def forall(p: (A) => Boolean): Boolean     //Tests whether a predicate holds for all elements of the list.
def filter(p: (A) => Boolean): List[A]       //Returns all elements of the list which satisfy a predicate.
reduceLeft((a, b) => a + b)     //Applies a binary operator to all elements of this list, going left to right.

All lists can be defined using two fundamental building blocks, a tail Nil and :: which is pronounced cons. Nil also represents the empty list. All the above lists can be defined as follows:

val fruit = "apples" :: ("oranges" :: ("pears" :: Nil))
val nums = 1 :: (2 :: (3 :: (4 :: Nil)))

// Empty List.
val empty = Nil

// Two dimensional list
val dim = (1 :: (0 :: (0 :: Nil))) ::
          (0 :: (1 :: (0 :: Nil))) ::
          (0 :: (0 :: (1 :: Nil))) :: Nil

def foreach(f: (A) => Unit): Unit // Applies a function f to all elements of the list

scala> val foo = List(List(1), List("a"), List(2.3))   //foo: List[List[Any]] = List(List(1), List(a), List(2.3)) 
scala> List.flatten(foo)             // List[Any] = List(1, a, 2.3)


val a:Map[Char,Int] = Map() // Empty hash table whose keys are strings and values are integers:
val a = Map("USA" -> "Washignton", "France" -> "Parice")      // A map with keys and values.
a += ("Germany" -> "Berlin")   //add an element
map1 ++ map2 //concat
map1.++(map2) //concat ++ as method name

a.keys.foreach{ myKey => 
                           print( "Key = " + myKey )
                           println(" Value = " + a(myKey) )}

Pattern Matching

def matchTest(x: Int): String = x match {
    case 1 => "one"
    case 2 => "two"
    case _ => "anything else"
expr match { case List(1,_,_) => " a list with three element and the first element is 1" case List(_*) => " a list with zero or more elements " case Map[_,_] => " matches a map with any key type and any value type " case _ => }

 In scala, _ acts similar to * in java while importing packages.

import scala.util.matching._    // imports all the classes in the package matching
import com.test.Fun._    // imports all the members of the object Fun. (static import in java)
import com.test.Fun.{ Foo => Bar , _ }    // imports all the members of the object Fun but renames Foo to Bar
import com.test.Fun.{ Foo => _ , _ }    // imports all the members except Foo. To exclude a member rename it to _

//assign a function to a new variable
Test { def fun = { // some code } val funLike = fun _ }
 def f() = 3 // We've defined a function that returns an Int
val g = f // f is invoked, thus g is 3
g() // Will not compile because g is an Int
val g = f _ // g is a function that returns an Int
g() // Returns 3
Other underscore uses
def foo(l: List[Option[_]]) = ...      //existential types
case class A[K[_],T](a: K[T])     //higher kinded type parameters
val _ = 5   //Ignored variables
List(1, 2, 3) foreach { _ => println("Hi") }   //Ignored parameters
Some(5) match { case Some(_) => println("Yes") }   //Wildcard patterns
import java.util._    //Wildcard imports
import java.util.{ArrayList => _, _}   //Hiding imports
def bang_!(x: Int) = 5   ///Joining letters to punctuation
def foo_=(x: Int) { ... }  //Assignment operators
List(1, 2, 3) map (_ + 2) //Placeholder syntax
List(1, 2, 3) foreach println _   //Partially applied functions


Null, null: Null is a trait, which (if you’re not familiar with traits) is sort of like an abstract class in Java. There exists exactly one instance of Null, and that is null.
The literal null serves the same purpose as it does in Java. It is the value of a reference that is not refering to any object. So if you write a method that takes a parameter of type Null, you can only pass in two things: null itself or a reference of type Null.
scala> def tryit(thing: Null): Unit = { println("That worked!"); }
tryit: (Null)Unit
scala> tryit("hey")
<console>:6: error: type mismatch;
 found   : java.lang.String("hey")
 required: Null
scala> val someRef: String = null
someRef: String = null
scala> tryit(someRef)
<console>:7: error: type mismatch;   // It’s a null reference to a String. It may be null at run-time, but compile-time type checking says this is a no-no.
 found   : String
 required: Null
 scala> tryit(null)
That worked!
scala> val nullRef: Null = null
nullRef: Null = null

 scala> tryit(nullRef)
That worked!
Nil: Empty list
scala> Nil
res4: Nil.type = List()
scala> Nil.length
res5: Int = 0
scala> Nil + "ABC"
res6: List[java.lang.String] = List(ABC)
scala> Nil + Nil
res7: List[object Nil] = List(List())

See? It’s basically a constant encapsulating an empty list of anything. It’s has zero length. It doesn’t really represent ‘nothingness’ at all. It’s a thing, a List. There are just no contents.

Nothing: If any of these is a little difficult to get, it’s Nothing. Nothing is another trait. It extends class Any. Any is the root type of the entire Scala type system. An Any can refer to object types as well as values such as plain old integers or doubles. There are no instances of Nothing, but (here’s the tricky bit) Nothing is a subtype of everything. Nothing is a subtype of List, it’s a subtype of String, it’s a subtype of Int, it’s a subtype of YourOwnCustomClass.

Remember Nil? It’s a List[Nothing] and it’s empty. Since Nothing is a subtype of everything, Nil can be used as an empty List of Strings, an empty List of Ints, an empty List of Any. So Nothing is useful for defining base cases for collections or other classes that take type parameters. Here’s a snippet of a scala session:

scala> val emptyStringList: List[String] = List[Nothing]()
emptyStringList: List[String] = List()
scala> val emptyIntList: List[Int] = List[Nothing]()
emptyIntList: List[Int] = List()
scala> val emptyStringList: List[String] = List[Nothing]("abc")
<console>:4: error: type mismatch;
 found   : java.lang.String("abc")
 required: Nothing
       val emptyStringList: List[String] = List[Nothing]("abc")

None: When you’re writing a function in Java and run into a situation where you don’t have a useful value to return, what do you do? There are a few ways to handle it. You could return null, but this causes problems. If the caller isn’t expecting to get a null, he could be faced with a NullPointerException when he tries to use it, or else the caller must check for null. Some functions will definitely never return null, but some may. As a caller, you don’t know. There is a way to declare in the function signature that you might not be able to return a good value, the throws keyword. But there is a cost associated with try/catch blocks, and you usually want to reserve the use of exceptions for truly exceptional situations, not just to signify an ordinary no-result situation.

Scala has a built-in solution to this problem. If you want to return a String, for example, but you know that you may not be able to return a sensible value you can return an Option[String]. Here’s a simple example.
scala> def getAStringMaybe(num: Int): Option[String] = {
     |   if ( num >= 0 ) Some("A positive number!")
     |   else None // A number less than 0?  Impossible!
     | }
getAStringMaybe: (Int)Option[String]
scala> def printResult(num: Int) = {
     |   getAStringMaybe(num) match {
     |     case Some(str) => println(str)
     |     case None => println("No string!")
     |   }
     | }
printResult: (Int)Unit
scala> printResult(100)
A positive number!
scala> printResult(-50)
No string!

Unit: This is another easy one. Unit is the type of a method that doesn’t return a value of any sort. Sound familiar? It’s like a void return type in Java. Here’s an example:
scala> def doThreeTimes(fn: (Int) => Unit) = {
     |   fn(1); fn(2); fn(3);
     | }
doThreeTimes: ((Int) => Unit)Unit
scala> doThreeTimes(println)
scala> def specialPrint(num: Int) = {
     |    println(">>>" + num + "<<<")
     | }
specialPrint: (Int)Unit
scala> doThreeTimes(specialPrint)

class Foo(x: Int) {
  def apply(y: Int) = {
    x*x + y*y

val f = new Foo(3)
f(4)   // returns 25

So basically, object(args) is just syntactic sugar for object.apply(args).


 val is executed when it is defined whereas a lazy val is executed when it is accessed the first time.
scala> class X { val x = { Thread.sleep(5000); 15 } }      //wait 5 seconds
defined class X

scala> class Y { lazy val y = { Thread.sleep(5000); 13 } }
defined class Y

scala> new X
res0: X = X@151cfdd

scala> new Y
res1: Y = Y@4f642c

scala> res0.x
res2: Int = 15

scala> res1.y     //wait 5 seconds
res3: Int = 13
 class LazyTest {
  lazy val msg = "OK"
is compiled to something equivalent to the following Java code:

class LazyTest {
  public int bitmap$0;
  private String msg;

  public String msg() {
    if ((bitmap$0 & 1) == 0) {
        synchronized (this) {
            msg = "OK";
            bitmap$0 = bitmap$0 | 1;
    return msg;


sbt is the standard build tool for Scala projects, has plug-ins that can generate Eclipse project files out of the sbt project definition.

Scala compiles to Java bytecode, meaning it runs on the JVM.
A function is given a set of inputs, a function should always return the same output.
every function must return a value, but that functions must inherently carry no intrinsic state from one call to the next.
immutable objects by default

 Scala is statically typed,
 heavy use of type inferencing

Scala does not require the semicolon,  termination is obvious by the line ending
Scala does not require the file containing a class definition to mirror the name of the class

Code Example (MyHello.scala)

object HelloWorld {         //singleton pattern: instance is created on demand, the first time it is used.
    define a function and assign it to a variable, (Unit is equivalent to void in java)
  def main(args: Array[String]): Unit                      = {                       // name : type
    System.out.println("Hello, Scala!")

$ scalac Hello.scala
$ scala HelloWorld     OR java -classpath %SCALA_HOME%\lib\scala-library.jar;. HelloWorld

System.out.println demonstrates Scala's fidelity to the underlying Java platform. Scala  make the full power of the Java platform available to Scala programs. (it will even allow a Scala type to inherit from a Java class, and vice versa)

Object: denotes singleton pattern, therefore main is not defined static.
static members (methods or fields) do not exist in Scala. Rather than defining static members, the Scala programmer declares these members in singleton objects.
a Scala application will allow both a class definition and an object definition of the same name.

Scala uses square brackets ("[]") instead of angle brackets ("<>") to indicate parameterized types

Some code evolution
 object Timer
  def oncePerSecond(): Unit =
    while (true)
      System.out.println("Time flies...")
  def main(args: Array[String]): Unit =
// pinging a remote
server) will need their own version of oncePerSecond

object Timer
  def oncePerSecond(callback: () => Unit): Unit =
    while (true)
  def timeFlies(): Unit =
  { Console.println("Time flies when you're having fun(ctionally)..."); }
  def main(args: Array[String]): Unit =
//Anonymius function
// genericize code in an entirely new dimension beyond inheritance.
//Strategy pattern
// create a high-level abstract function that does one thing, let it take a block of code (an anonymous function) as
a parameter, and call that block of code from within the high-level function
 //return arguments that start with G
object HelloWorld
  def main(args: Array[String]): Unit = {
    args.filter( (arg:String) => arg.startsWith("G") )
        .foreach( (arg:String) => Console.println("Found " + arg) )
class Array[A]
    // ...
   def filter  (p : (A) => Boolean) : Array[A] = ... // not shown
Listing 7 declares that p is a function that takes a parameter of the generic type
specified by A and returns a boolean. The Scala documentation states that filter
"Returns an array consisting of all elements of this array that satisfy the predicate



simple message oriented programming model for multi-threading
serializes access to shared resources using queues and function passing

run shell commands (Scala ProcessBuilder)

use Scala's sys.process library:
scala> import sys.process._
import sys.process._
scala> "ls /home/dcs/".!
res1: Int = 0

Other hints

<adelbertc> val validFiles = myFiles.filter(filepath => filepath.size <= 10)

you could follow with a .toVector or something like that to get a strict collection with the results
! Stream(Some(1), None, Some(2), None, None).flatten.toList // mor8a
<luft> ok, how do I check if A <:< object x when A <: AnyRef : ClassTag?
<multibot_>  List[Int] = List(1, 2)
<tpolecat> ! Stream(Some(123), None, Some(456), None, None).flatten.mkString
<multibot_>  String = 123456

<Naktibalda> you never need a for loop in scala
<tpolecat> mor8a: no, explicit looping is very rare in scala
<_pa_> Naktibalda: depends on what you mean
<_pa_> for (x <- xs) bar(x)
<_pa_> Is that a for loop? =)
<dfrey> _pa_: Wouldn't you just do this though? xs.foreach(bar)
<ecuderpam> dfrey: The for-comprehension desugars to something like that.
<_pa_> dfrey: they're equivalent

<dfrey> _pa_: They are equivalent yes, but isn't it preferred to use foreach for simple cases?
<_pa_> By whom?
<_pa_> I find that the for comprehension often cleans things up
<ecuderpam> the passive voice is said to prefer X
<qu1j0t3> ecuderpam: Experts agree
<d_m_> dfrey: just preferences. i like foreach better personally.
<_pa_> When you have more than one monadic operation

after installing scala you can just start coding!
$ scala
scala> 2+3
res0: Int = 5
scala> "hello" + res0  //access to previous temp variables
res1: java.lang.String = hello5
scala>      //click tab for auto complete
scala>res2.toUpperCase    //no parenthesis needed


To parse a json file.
 import scala.util.parsing.json.JSON
val json = JSON.parseFull(Source.fromFile(filename).mkString)
    val map:Map[String,Any] = json.get.asInstanceOf[Map[String, Any]]
    val entities : List[Any] = map.get("targets").get.asInstanceOf[List[Any]]
    entities.foreach( target => {
      val entity : Map[String,Any] = target.asInstanceOf[Map[String, Any]]
      val alias = entity.get("alias").get.asInstanceOf[List[String]]
      entity_list.add(new Entity(entity.get("entity_type").toString, 
        entity.get("group").toString, entity.get("target_id").toString, alias))
    "$schema": "", 
    "targets": [
            "entity_type": "FAC", 
            "group": "danville", 
            "target_id": "",
            "alias": ["Stuart Powell Field"]
            "entity_type": "FAC", 
            "group": "danville", 
            "target_id": "",
            "alias": ["CorbinSpeedway", "Corbin Speedway"]
            "entity_type": "FAC", 
            "group": "deeplearning", 
            "target_id": "",
            "alias": ["IDSIA"]

TODO read:
functional features (such as pattern matching)
operator overloading
generics with "upper and lower type bounds,"
Strategy pattern

Promises (Futures)

A typical future looks like this:

val inverseFuture: Future[Matrix] = Future {
  fatMatrix.inverse() // non-blocking long lasting computation

Or with the more idiomatic:

implicit val ec: ExecutionContext = ...
val inverseFuture : Future[Matrix] = Future {
} // executionContext is implicitly passed

Both code snippets delegate the execution of fatMatrix.inverse() to an ExecutionContext and embody the result of the computation in inverseFuture