-1

以下代码在 scala shell 中不起作用,但它在 IDE 中起作用,任何人都可以在 scala-shell 中使用对象类型作为方法参数,谢谢。

scala> object A {
     | }
defined object A

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

3 回答 3

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
于 2018-11-21T12:41:13.690 回答
0

只需添加特征 A :

trait A
object A extends A
def f(a:A) :Unit = { }
于 2018-11-21T12:38:51.410 回答
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
于 2020-10-12T08:24:46.183 回答