-1

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 = {
zjffdu
  • 25,496
  • 45
  • 109
  • 159
  • Just a thought, a function that accepts a unique singleton as its sole argument, is it not just a [`thunk`](https://en.wikipedia.org/wiki/Thunk)? – Yaneeve Nov 21 '18 at 13:25

3 Answers3

1

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
Mahmoud Hanafy
  • 1,861
  • 3
  • 24
  • 33
0

Just add trait A :

trait A
object A extends A
def f(a:A) :Unit = { }
Vladimir Berezkin
  • 3,580
  • 4
  • 27
  • 33
0

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
Tomer Shetah
  • 8,413
  • 7
  • 27
  • 35