Unable to use object type as method argument in scala shell

127 Views Asked by At

The following code doesn't' work in scala shell, but it works in IDE, does anyone how can I use object type as method parameter in scala-shell, thanks.

scala> object A {
     | }
defined object A

scala> def f(a:A) :Unit = {
     | }
<console>:63: error: not found: type A
       def f(a:A) :Unit = {
3

There are 3 best solutions below

0
On

What do you mean by works in IDE? I created a project with one file, HelloWorld1, where its content is:

object HelloWorld1 extends App {
  
  override def main(args: Array[String]): Unit = {
    object A {

    }

    def f(a:A) :Unit = {}
  }
}

When compiling I am getting the following error:

HelloWorld1.scala:8:13
not found: type A
    def f(a:A) :Unit = {}

As mentioned in the two answers above, you can either do:

def f(a:A.type) :Unit = {}

Or define trait instead of object:

trait A
0
On

Just add trait A :

trait A
object A extends A
def f(a:A) :Unit = { }
0
On

You can use Object.type like this:

scala> object A {}
defined object A

scala> def f(a: A.type) = println("hello world")
f: (a: A.type)Unit

scala> f(A)
hello world