0

I want to declare a var that can hold a function, but I want to assign the function only later.

How do I declare such a var, e.g. when it takes no parameters and returns nothing?

I tried this but that's not accepted:

private var myFunction : ()

Later in the code, I'd assign code to it like this, I imagine:

myFunction = () => { doSomething() }
Thomas Tempelmann
  • 11,045
  • 8
  • 74
  • 149

1 Answers1

5

Like so:

  def doSomething(): Unit = ???

  class A {
    private var m1: Function0[Unit] = _

    // later down the line
    m1 = () => { doSomething() }

    private var m2: () => Unit = _

    // later down the line
    m2 = () => { doSomething() }
  }

Just declare the type of the function using function literal syntax, or with one of the FunctionN traits.

Edit

Your mistake was declaring myFunction with invalid syntax.

Syntax is [visibility] {var|val|lazy val} {variable-name}[:<variable-type>}[=<value]

Where [] denotes optional parts and {} mandatory parts.

Visibility is assumed public if you omit it. As to the underscore you can check its meaning in this SO post

Thomas Tempelmann
  • 11,045
  • 8
  • 74
  • 149
pedromss
  • 2,443
  • 18
  • 24
  • Ah, so my mistake was that I didn't understand that I have to assign _something_ to the var. And "_" is the best solution, I assume? (I only am trying to fix some Scala code someone else has written, I'm not planning to learn the compile language to write my own apps in it. Most of it is pretty easy to understand when knowing other langs, such as Swift, anyway). – Thomas Tempelmann Sep 02 '17 at 13:41
  • My main problem was apparently to figure out what the "variable-type" for a function signature with no return value is. – Thomas Tempelmann Sep 03 '17 at 10:24