【问题标题】:found scala.Int(0) required Int 0发现 scala.Int(0) 需要 Int 0
【发布时间】:2014-11-26 14:18:54
【问题描述】:

我是 scala 的新手,我正在运行书中的一些练习来实现一个列表。

我有一个方法sum 来添加列表中的所有数字。我使用 TDD 方法,所以首先我只返回 0 使其失败。但是编译抱怨类型不匹配。它期望Int,但收到scala.Int

def sum[Int](as: MList[Int]): Int = 
{
    0
}

投诉信息:

MList.scala:17: error: type mismatch;
 found   : scala.Int(0)
 required: Int
    0
    ^
one error found

所以我尝试改成

def sum[scala.Int](as: MList[scala.Int]): scala.Int = 
{
    0
}

编译器抱怨. 不应该存在于[scala.Int] 中。

我还尝试将 0 转换为 new Int(0)Int(0)(Int)0new Int(我来自 C++)来匹配返回类型,但它也不起作用。

scala.Int(0) 和文字 0 有什么区别?是不是我忘记包含一些像内置号码包这样的包?

【问题讨论】:

    标签: scala


    【解决方案1】:

    问题是,这里

    def sum[Int](as: MList[Int]): Int = 0
           ^^^^^
    

    您正在声明一个名为 Int 的新类型,它会影响 scala.Int。 您的sum 方法是通用的,Int 是其类型参数的名称。

    只需去掉类型参数即可。

    def sum(as: MList[Int]): Int = 0
    

    【讨论】:

    • 谢谢!有用。因为我之前实现的方法是def apply[A](as: A*): MList[A] = {...},所以我只是把A换成Int。哈哈
    猜你喜欢
    • 2015-03-20
    • 1970-01-01
    • 2010-11-18
    • 2014-11-09
    • 2022-01-07
    • 1970-01-01
    • 2016-07-14
    • 1970-01-01
    • 2016-12-01
    相关资源
    最近更新 更多