gpt4 book ai didi

scala - 定义我自己的 toInt 方法时 scala 中的异常

转载 作者:行者123 更新时间:2023-12-04 07:14:40 24 4
gpt4 key购买 nike

为什么这段代码会抛出异常?

val x = new { def toInt(n: Int) = n*2 }
x.toInt(2)
scala.tools.nsc.symtab.Types$TypeError: too many arguments for method toInteger: (x$1: java.lang.Object)java.lang.Integer
at scala.tools.nsc.typechecker.Contexts$Context.error(Contexts.scala:298)
at scala.tools.nsc.typechecker.Infer$Inferencer.error(Infer.scala:207)
at scala.tools.nsc.typechecker.Infer$Inferencer.errorTree(Infer.scala:211)
at scala.tools.nsc.typechecker.Typers$Typer.tryNamesDefaults$1(Typers.scala:2350)
...

我正在使用 Scala 2.9.1.final

最佳答案

显然是编译器错误(编译器崩溃,REPL 告诉您 That entry seems to have slain the compiler. )。这并不表示您的代码有任何问题。

您正在创建 AnyRef{def toInt(n: Int): Int} 类型的单个实例,所以像 Kyle 建议的那样创建一个单例对象可能是一个更好的方法。或者创建一个你实例化的命名类/特征,它工作正常。

关于scala - 定义我自己的 toInt 方法时 scala 中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9712788/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com