开发者

How do I use POJO equivalents in Scala?

开发者 https://www.devze.com 2023-03-21 00:49 出处:网络
Suppose I have the following class SimpleClass (myInt: Int, myString: String) { } What is wrong with the following?

Suppose I have the following

class SimpleClass (myInt: Int, myString: String) {

}

What is wrong with the following?

val mySim开发者_开发知识库ple = new SimpleClass(1, "hi")
println(mySimple.myInt)


If you want the contructor parameters to be available as fields of the class, you have to declare them as vals or vars:

class SimpleClass (val myInt: Int, val myString: String) {

}


The java equivalent of your Scala definition is:

public class SimpleClass {
   public SimpleClass( int myInt, String myString ) {
   }
}

No wonders it doesn't work...

Hey dude, that's your 17th scala question and you are still troubled by the very basics of the language. Perhaps you should take an afternoon and read some of tutorial on-line (or some book) to consolidate your knowledge. I can suggest:

  • http://www.codecommit.com/blog/scala/roundup-scala-for-java-refugees
  • http://www.ibm.com/developerworks/java/library/j-scala02198/index.html (see listings 11-13)


For the full POJO experience™, including equality, hashCodes and sane implementation of toString... You'll want case classes:

case class SimpleClass(myInt: Int, myString: String)

val mySimple = SimpleClass(1, "hi")
println(mySimple.myInt)

Parameters to a case class are automatically made into vals. You can explicitly make them vars if you wish, but this this sort of thing is typically frowned upon in Scala - where immutable objects are favoured.


The problem is that you are calling the SimpleClass.myInt getter method but you didn't define a getter method anywhere. You need to define the SimpleClass.myInt getter method or even better yet, get Scala to automatically define it for you:

class SimpleClass(val myInt: Int, myString: String) {}
0

精彩评论

暂无评论...
验证码 换一张
取 消