0

I have an already existing class written in Java (lets say this class is called X) that contains a field / member named type.

I now want to write a Scala class / object that creates an object of type X and access the type member of that object.

Yet, since type is a keyword in Scala, this does not work. The error message in Eclipse is: identifier expected but 'type' found.

Question: Is it possible to access that field without renaming it?


A working example:

Java Class:

public class X {
  public final int type = 0;
}

Scala App:

object Playground extends App {
  val x : X = new X();
  System.out.println(x.type); // This does not work!
}
0

2 Answers 2

1

Either use backticks or define a gettter.

object Playground extends App {
  val x : X = new X();
  System.out.println(x.`type`)
}

Or using a getter,

public class X {
  public int type = 0;

  public int getType() {
    return type;
  }
}

object Playground extends App {
  val x : X = new X();
  System.out.println(x.getType());
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Since the fields are final in the original application (just edited the question), we didn't write getters on purpose, but good idea!
I don't like Getters either, too much verbosity. @Getter for static variable does not sound great though.
1

You can use reserved words as names by using back ticks, e.g. type. For more information, see previous questions: Is there a way to use "type" word as a variable name in Scala?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.