gpt4 book ai didi

Scala 代码 - 错误 : missing parameter type error

转载 作者:行者123 更新时间:2023-12-02 15:38:53 25 4
gpt4 key购买 nike

这段代码有什么问题?

object Numbers extends App {

def decode(number: Int) : String = number match {
case _ if _ % 15==0 => "fizzbuzz"
case _ if _ % 3==0 => "fizz"
case _ if _ % 5==0 => "buzz"
case _ => _.toString
}

val test = List(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)
test.map(decode).foreach(println)
}

我收到以下错误:

error: missing parameter type for expanded function
The argument types of an anonymous function must be fully known. (SLS 8.5)
Expected type was: String
case _ if _%15==0 => "fizzbuzz"

为什么编译器不知道参数类型?谢谢

最佳答案

(_ % 15 == 0) 扩展为函数 (x: ?) => x % 15 == 0。与其他 if 检查相同。
编译器无法推断它,因为它没有关于参数的信息,它是一个新名称,与 case _ 中的前一个下划线无关。所以你不能在那里使用下划线来引用匹配的名称,你必须实际为其分配一个名称,如 case x if x % 15 == 0

关于Scala 代码 - 错误 : missing parameter type error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11901035/

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