简体   繁体   中英

See values of Class methods in Scala

I'm brand brand new to Scala, but I'm having trouble debugging my stuff. I have this "test" in a book I'm reading to make a Family class with a familySize() method. My solution was something like:

class Family(names:String*) {
  def familySize():Int = {
    args.length
  }
}
val family1 = new Family("Mom", "Dad", "Sally", "Dick")
family1.familySize() is 4

However, this produces an error:

scala:8: error: value is is not a member of Int
family1.familySize() is 4
                     ^
one error found

My problem is, I have no idea how to see what args.length equals. I tried just doing family1.familySize() but when I run it it doesn't return anything.

First you don't have args :

class Family(names: String*) {
  def familySize(): Int = names.length
}

You have a couple of options:

1) Simple equality operator

val family1 = new Family("Mom", "Dad", "Sally", "Dick")
family1.familySize() == 4

2) In Scalaz there is a JavaScript like typesafe equality operator:

val family1 = new Family("Mom", "Dad", "Sally", "Dick")
family1.familySize() === 4

which throws an exception if operands have different types

3) Different test libraries like: Scalatest , Specs2 or Scalacheck . For example in ScalaTest with must matchers:

family1.familySize must equal (4)

args doesn't exist, it's names :

class Family(names: String*) {
  def familySize(): Int = names.length
}

val family1 = new Family("Mom", "Dad", "Sally", "Dick")
println(family1.familySize()) // will output 4

You can also avoid curly braces around names.length being a one-liner.

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