found: Unit required: Int - How to correct this?

后端 未结 3 858
萌比男神i
萌比男神i 2021-01-15 22:55
scala> class Rectangle (Length: Int, Width: Int) {; def getLlength (): Int = println (Length); def getWidth ():Int = println (Width); }
:11: error:         


        
3条回答
  •  [愿得一人]
    2021-01-15 23:46

    I can tell you where you're going wrong, but it's not entirely obvious what it is you want to do here.

    You've declared the getLlength (sic) method to be returning a type of Int. However, the body of this method is just a println call, and so it will return the result of this call. println has a return type of Unit (since it returns nothing, and is executed only for its side effects).

    Hence your method is declared to return Int, but you've implemented it in such a way that it's return type would be Unit. Which is why you get a compile-time error.

    Do you want your method to return the length? If so, you should just return Length rather than printing it. However, an even better way to do this is Scala would be to mark the constructor parameter as a val, which will automatically generate an accessor for it:

    class Rectangle(val Length: Int, ...
    

    Now anyone with a reference to e.g. a Rectangle rect object can call rect.Length to get the length. This is in fact the preferred way to access fields and field-like properties in Scala, rather than the getFoo convention that Java uses.


    If you really just want a "container" class that allows someone to access named parameters, consider case classes. You could define a functionally equivalent class as

    case class Rectangle(length: Int, width: Int)
    

    This automatically generates accessor methods for both fields, sensible toString(), equals() and hashCode() implementations - and you also get pattern matching as an added bonus.

    Any time you want a class which is mainly/entirely just a bundle of fields, case classes should be your starting point.


    Note as well that variables in Scala are lowerCamelCase by convention. Declaring fields/constructor parameters with upperclass names (i.e. Length instead of length) is surprisingly confusing for people reading your code, so you will do yourself and everyone else a favour by sticking to convention.

提交回复
热议问题