简体   繁体   中英

Def vs. val, functional syntax not working in Scala.js?

To give you a minimal example:

object Main extends JSApp
{
   val someThing: String = determineSomething("test")   

   def main(): Unit =
   {
       println(someThing)
   }
}

Now, two possibilities here:

private def determineSomething(s: String): String = "succeeded"

If the project is executed like this, well, I get a log entry saying

succeeded

But when I use the more functional syntax:

private val determineSomething: (s: String) => "succeeded"

I get

TypeError: this.determineSomething$1 is null

I am curious as to the why this happens as in the (JVM) repl, both ways work perfectly fine.

I think what you want is something like this:

object Main extends JSApp {
  private val determineSomething: String => String = (s: String) => "succeeded"

  val someThing: String = determineSomething("test")   

  def main(): Unit = {
    println(someThing)
  }
}

The declaration of determineSomething needs to come before the declaration of something , otherwise the former will be uninitialized when the compiler attempts to initialize the latter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM