【问题标题】:Illegal start of declaration非法开始申报
【发布时间】:2018-07-21 16:41:11
【问题描述】:

我有以下 Scala 代码:

object Solution {
    def main(args: Array[String]) {
        val List(n, m) = readLine().split(" ").map(_.toInt).toList;
        val knowledge: List[Set[Int]] = (0 until n).map( _ => {
            val knows: List[Char] = readLine().toList;
            (0 until m).toSet.flatMap(topic: Int => {
                knows(topic) match {
                    case '1' => Set(topic);
                    case _ => Set[Int].empty;
                } 
            });
        }).toList;
        val teams: List[Int] = knowledge.grouped(2).map{ case(x, y) => x ++ y }.map(_.size);
        val best: Int = teams.max;
        val count = teams.filter(_ == max);
        println(best + " " + count);
    }
}

在它上面,我收到了这个错误:

Solution.scala:16: error: illegal start of declaration
                knows(topic) match {Solution.scala:

在这一行:

knows(topic) match {

我不明白出了什么问题。

我在 flatMap 的正文中使用了 match

知道这段代码有什么问题吗?

【问题讨论】:

    标签: scala


    【解决方案1】:

    使用显式类型,您需要

    (topic: Int) =>
    

    根据匿名函数的语法

    https://www.scala-lang.org/old/node/133

    根据this answer,也可以把类型移到

    (0 until m).toSet[Int].flatMap(topic => {
    

    【讨论】:

    • 另一种方式是写.flatmap{ topic => ... }
    • 在某些情况下是的,但是(我不完全知道为什么)编译器无法推断这里的类型,所以: Int 是必要的
    • 查看 REPL 中的 (0 to 10).toSet.flatMap(t => Set(t))Set(1, 2, 3).flatMap(t => Set(t)) 的对比
    • 哦..这是真的..这两种情况下的不同行为..在第一种情况下无法推断类型..它在第二种情况下推断出类型。这里到底发生了什么?
    • @RAGHHURAAMM 我被指向这个 qu 以获得答案stackoverflow.com/q/13130013/5986907
    猜你喜欢
    • 2015-12-24
    • 2015-10-15
    • 2017-11-21
    • 1970-01-01
    • 2023-03-26
    • 2011-04-26
    • 2014-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多