beginner beginner - 2 months ago 13
Scala Question

Can't import object in Intellij Scala

I am working through Chiusano's Functional Programming in Scala. In the 3rd chapter relating to functional data structures, he provides example code to demonstrate the concept of Singly Linked List in Listing 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: _*))
}


I named this file 'listing.sc' and saved it in the 'datastructures' package in /src/main/scala, as per the attached directory structure shown:

Directory structure

I am trying to import the List object into a different file called test.sc. I have the following code below:

import datastructures.List

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


However this fails with the error : Cannot resolve symbol List. I have tried importing datastructures._ but this didn't work as well.

Import error
Can someone point me in a direction towards fixing this?

Thanks so much

Answer

.sc files are worksheet files wich is a construct used to quickly evaluate and test scala code.

Worksheet sources cannot be used as scala source code. If you want to use the code in other classes or worksheet you should change the file extension to .scala