[scala-user] How to, from Java code, access fields of Scala classes??

636 views
Skip to first unread message

Nick Rudnick

unread,
Mar 3, 2012, 10:58:33 AM3/3/12
to scala-user
Dear all,

googling quite a good deal didn't reveal an answer for a question which should be interesting many people:

Doing Java->Scala conversions, I several times stumbled over impossibility to access Scala class fields from Java code – with messages like 

"java.lang.IllegalAccessError: tried to access field somePackage.SomeClass.x from class OtherClass"

or

"error: defaultFont has private access in SomeClass,"  

though both field were actually public in their Scala classes:

case class Location(var x:Int, var y:Int) extends Serializable {

class GridWorldView(model:GridWorldModel) extends JFrame {
    ...
    var defaultFont:Font= new Font("Arial", Font.BOLD, 10)

As I nowhere read this to be prohibited, and even fiddling around led to inconclusive results, e.g. model was readable, even when move down,

class GridWorldView() extends JFrame {
    ...
    var defaultFont:Font= new Font("Arial", Font.BOLD, 10)
    var model:GridWorldModel= _

So finally, I've become curious:

o   are there specs I have overseen forbidding this?
o   if no, did anybody here experience success doing it? (how...??)
o   if yes, did anybody here experience similar problems?
o   is there a place where such issues are discussed?

Thank you a lot in advance, Nick

Eugen Labun

unread,
Mar 3, 2012, 11:38:40 AM3/3/12
to scala...@googlegroups.com
Hi Nick,

a Scala ´var x´ (as a member of a class/trait) from Java p.o.v is three things:

1) private field ´x´
2) public getter method ´x()´
3) public setter method ´x_=(...)´.

So when you replace ´x´ with ´x()´ in Java code, it should work.
When not, could you prepare a minimal example that reproduces the problem?

EL

Tom Switzer

unread,
Mar 3, 2012, 11:45:13 AM3/3/12
to Nick Rudnick, scala-user
Eugen's answer nailed it. However, you may be interested in the @BeanProperty annotation if you are doing a lot of Java interop. It'll generate Java bean style getters/setters for you:

import scala.reflect.BeanProperty

class MyBean {
  @BeanProperty var prop: String = _
}

val bean = new MyBean
bean.setProp("Hi there!")
println(bean.getProp())
Reply all
Reply to author
Forward
0 new messages