![](/img/trans.png)
[英]Scala use argument which is passed to construct the object in other method of the object
[英]Unable to use object type as method argument in scala shell
下面的代碼在 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 = {
您可以像這樣使用 Object.type:
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 = { }
在 IDE 中工作是什么意思? 我用一個文件HelloWorld1
創建了一個項目,它的內容是:
object HelloWorld1 extends App {
override def main(args: Array[String]): Unit = {
object A {
}
def f(a:A) :Unit = {}
}
}
編譯時我收到以下錯誤:
HelloWorld1.scala:8:13
not found: type A
def f(a:A) :Unit = {}
正如上面兩個答案中提到的,你可以這樣做:
def f(a:A.type) :Unit = {}
或者定義特征而不是對象:
trait A
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.