我有以下代码:
import com.github.nscala_time.time.Imports._
class Account {
def balance(date: DateTime): Double = {
/* some logic that calculates balance on given date */
val calculatedBalance = 42
calculatedBalance
}
def balance: Double = balance(DateTime.now)
}
class Deposit(val interestRate: Double) extends Account {
override def balance(date: DateTime): Double = {
/* some logic that calculates balance for deposit account */
val calculatedBalance = 100 * interestRate;
calculatedBalance
}
}
我尝试通过以下方式使用这些类:
val simpleAccount = new Account
val depositAccount = new Deposit(0.1)
val simpleBalanceOnDate = simpleAccount.balance(DateTime.now + 1.month) // A
val depositBalanceOnDate = depositAccount.balance(DateTime.now + 1.month) // B
val simpleBalance = simpleAccount.balance // C
val depositBalance = depositAccount.balance // D
情况
A
,B
和C
编译没有任何错误,但是对于D
行,我看到错误消息:Error:(28, 38) ambiguous reference to overloaded definition,
both method balance in class Deposit of type (date: com.github.nscala_time.time.Imports.DateTime)Double
and method balance in class Account of type => Double
match expected type ?
val depositBalance = depositAccount.balance
^
您能解释一下为什么
D
时出现编译错误以及为什么没有C
时出现编译错误吗?提前致谢!
最佳答案
我想编译器对无参数方法继承感到困惑,尽管我不能诚实地解释为什么,对于一个快速的解决方案,它应该可以工作:
class Account {
{ ... }
def balance(): Double = balance(DateTime.now)
}
val depositAccount = new Deposit(0.1)
val depositBalance = depositAccount.balance()
为什么发生这种情况对我来说还是个未知数,也许其他人知道scala编译器如何看到无参数方法继承。
还要阅读,特别是Programming in Scala:
abstract class Element {
def contents: Array[String]
val height = contents.length
val width =
if (height == 0) 0 else contents(0).length
}