Scala “constructor Stopwatch cannot be accessed in class Main”


April 2019


2.8k time


Summary on resolution, I thought I was dealing with a Scala problem but it turns out Stopwatch and Scala Logging have private constructors, and I was not calling the proper public methods to instantiate them. gzm0's answer below points this out.

Trying to use Guava Stopwatch and Scala Logging, no matter whether I create a new Stopwatch() or new Logger() in Main or in an instantiated class I get this error with gradle run:

constructor Logger in class Logger cannot be accessed in class RedBlackTree4150
var loggerInst = new Logger()
constructor Stopwatch in class Stopwatch cannot be accessed in class RedBlackTree4150
var stopWatchInst = new Stopwatch()

If this is a duplicate of this or this question I don't know enough to realize it. I looked at this question but it doesn't have an accepted answer, and I tried (just for fun) to take my parens off my constructor calls to no avail.

Writing my first Gradle/Scala project for a Analysis of Algorithms assignment. I think if I was in Java I would be asking about static vs. non-static, not sure if that's the type of issue I am dealing with. Scala is not part of the assignment so I am not using a homework tag.

Here's how I am calling them and the first part of my program, the full .scala file and the build.gradle are on Github

import com.typesafe.scalalogging.slf4j.Logger
import scala.collection.immutable.TreeMap
import java.util.concurrent.TimeUnit

object Main extends App {
  // var rbtree = new RedBlackTree4150(logger, stopWatch)
  var rbtree = new RedBlackTree4150()
// class RedBlackTree4150 (var loggerInst: Logger, var stopWatchInst: Stopwatch) {
class RedBlackTree4150() {
  var loggerInst = new Logger()
  var stopWatchInst = new Stopwatch()

As you can see I have tried simplifying this by making it all one Object, and by instantiating Logger and Stopwatch in Main and passing them to the class (bad idea I know) but none of that works. What simple Scala thing am I missing here? Thanks.

Otherwise I believe I have all my dependencies in the project properly, and I get the same error on command line.

I do have one more error I posted as a separate question here, just in case it's relevant, the error is:

/home/jim/workspace/Scala/RedBlackTree4150/src/main/scala/Main.scala:36: value map is not a member of Double
  timingsMap = for (i <- powersList; j <- runTest(i)) yield i -> j

1 answers


The constructors of both Stopwatch and Logger are private. You need to use factory methods to instantiate them.

In case of the Stopwatch, you could use the createUnstarted() method:

val stopwatch = Stopwatch.createUnstarted()

In case of Logger, you must use the apply method. However, it requires an underlying SLF4J logger. You can create one through SLF4J's LoggerFactory:

import org.slf4j.LoggerFactory
val logger = Logger(LoggerFactory.getLogger(getClass))