今天春天 今天春天 - 1 month ago 17
Scala Question

Scala: use case class from Main

In my project there is a Main object:

object Main extends App {
println("Hello world")
}


and another one:

object Abc {
abstract class BAbcTest
case object Meow extends BAbcTest

...


def domeow(b: BAbcTest): BAbcTest = b match { ... }
}


How can I call
domeow
from
Main
? I am using sbt and when I type in
run
there, it just prints "Hello World.".

I tried to write
domeow(Meow)
in the Main object but it keeps saying


not found: value Meow

Answer

Just do Abc.domeow(Abc.Meow) inside the Main object. Everything inside the Main will be executed in the main method as Main extends App.

You have to do Abc.Meow inorder to refer to Meow object from Main object or import Abc using import Abc._ inside the Main

 object Main extends App {
    println("Hello world")
    Abc.domeow(Abc.Meow)
  }

or import Abc._

object Main extends App {
    println("Hello world")

    import Abc._

    Abc.domeow(Meow)
  }


  object Abc {
    abstract class BAbcTest
    case object Meow extends BAbcTest
    def domeow(b: BAbcTest): BAbcTest = b match { case Meow => Meow }
  }

do Abc.test(1) inside the Main object.

As Main extends App. All code inside the Main will be executed inside the main method of the object Main. So when you do sbt run all the code inside the Main object executes.

object Main extends App {
  println("Hello world")
  println(Abc.test(1))
}

object Abc {
  def test(a: Int): Int = a match { ... }
}

Scala REPL

scala> object Abc {
    def test(a: Int): Int = a match { case 1  => 1}
  }
defined object Abc

scala> object Main extends App {
    println("Hello world")
    println(Abc.test(1))
  }
defined object Main

scala< Main.main(Array(""))
Hello world
1
Comments