以下代码在 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 = {
以下代码在 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 = {
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
只需添加特征 A :
trait A
object A extends A
def f(a:A) :Unit = { }
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