【问题标题】:Can't import object in Intellij Scala无法在 Intellij Scala 中导入对象
【发布时间】:2016-09-25 08:16:38
【问题描述】:

我正在研究 Chiusano 在 Scala 中的函数式编程。在与函数式数据结构相关的第 3 章中,他提供了示例代码来演示清单 3.1 中的单链表的概念:

package datastructures
sealed trait List[+A]

case object Nil extends List[Nothing]
case class Cons[+A](head: A, tail: List[A]) extends List[A]

object List {
  def sum(ints: List[Int]): Int = ints match {
    case Nil => 0
    case Cons(x, xs) => x + sum(xs)
  }

  def product(ds: List[Double]): Double = ds match {
    case Nil => 0
    case Cons(0.0, _) => 0.0
    case Cons(x, xs) => x * product(xs)
  }

  def apply[A](as: A* ): List[A] =
    if (as.isEmpty) Nil
    else Cons(as.head, apply(as.tail: _*))
}

我将此文件命名为“listing.sc”,并将其保存在 /src/main/scala 中的“数据结构”包中,根据所显示的附加目录结构:

我正在尝试将 List 对象导入到另一个名为 test.sc 的文件中。我有以下代码:

import datastructures.List

val ex1: List[Double] = Nil
val ex2: List[Int] = Cons(1, Nil)
val ex3: List[String] = Cons("a", Cons("b", Nil))

但是这失败并出现错误:无法解析符号列表。我尝试过导入数据结构。_ 但效果不佳。

有人可以指出我解决这个问题的方向吗?

非常感谢

【问题讨论】:

    标签: scala intellij-idea functional-programming


    【解决方案1】:

    .sc 文件是工作表文件,用于快速评估和测试 Scala 代码。

    工作表源不能用作 scala 源代码。如果您想在其他类或工作表中使用代码,您应该将文件扩展名更改为.scala

    【讨论】:

    • 感谢 Sascha,这帮助很大
    猜你喜欢
    • 2019-05-25
    • 2015-12-02
    • 1970-01-01
    • 2012-09-27
    • 1970-01-01
    • 1970-01-01
    • 2017-12-15
    • 1970-01-01
    • 2020-10-18
    相关资源
    最近更新 更多