Anton Ermakov Anton Ermakov - 1 year ago 69
Scala Question

Scala object: pass to or return from function

Given class:

object Obj {...}

Is there a way to pass object to function or return object from function like this:

def f(x: Obj): Boolean
def g(x: Boolean): Obj

Both two examples causes CE (Compile Error).

I know that it's possible use object directly by name
in body of function f so first example mostly theoretical than practical. But for second example i can't see alternate ways.

Apparently both examples are 'antipatterns' and scala objects should not be applied such way.

Answer Source

Use Obj.type:

scala> object O
defined object O

scala> def f(o: O.type) = 42
f: (o: O.type)Int

scala> f(1)
<console>:14: error: type mismatch;
 found   : Int(1)
 required: O.type

scala> f(O)
res1: Int = 42
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download