简体   繁体   中英

scala assignment operator _= not working in trait

Here is the code:

trait MacApp {
    def dockerIcon_=(s: String) = println("setting docker icon...")
}

object Main extends App with MacApp {
    dockerIcon = "apple"
}

The scalac complains this:

Main.scala:6: error: not found: value dockerIcon
    dockerIcon = "apple"
        ^
one error found

I see scala-swing library use _= a lot, eg, https://github.com/scala/scala-swing/blob/2.0.x/src/main/scala/scala/swing/Label.scala#L28

Thanks!

You need both getter and setter:

scala> :pa
// Entering paste mode (ctrl-D to finish)

trait MacApp {
    def dockerIcon_=(s: String) = println("setting docker icon...")
    def dockerIcon = 42
}
object Main extends App with MacApp {
    dockerIcon = "apple"
}

// Exiting paste mode, now interpreting.

defined trait MacApp
defined object Main

scala> Main main null
setting docker icon...

http://www.scala-lang.org/files/archive/spec/2.11/06-expressions.html#assignments

Your expectations about the pair of members are established earlier at:

http://www.scala-lang.org/files/archive/spec/2.11/04-basic-declarations-and-definitions.html#variable-declarations-and-definitions

You're trying to assign to a function? I don't think that _= Swing code is using an operator, I think it's just an odd name...possibly for some obscure Java compatibility reason that escapes me at the moment.

But def defines a function, not a value, so you can't assign to it; you have to call it. Check out this console fragment:

scala> def text_=(s: String) = s + "foo"
text_$eq: (s: String)String 

scala> text_=("bar")
res3: String = barfoo

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