Reputation: 131
I'm a newbie to Scala. I'm still trying to understand how method return types work in Scala. I have a base class as follows:
abstract class CustomNumber {
def value: AnyVal
override def toString = value.toString
}
And a subclass which looks like:
class CustomInteger(val input: Integer) extends CustomNumber {
def value = input
}
But when I try to run this code, I get the error:
the result type of an implicit conversion must be more specific than AnyVal
def value = input
type mismatch;
found : Integer
required: AnyVal
def value = input
Why would it be an error to return Integer
as AnyVal
if it is just a subclass?
Upvotes: 0
Views: 480
Reputation: 1303
I think just change it to:
class CustomInteger(val input: Int) extends CustomNumber {
def value = input
}
Int
is the scala type/class for integer. Have a look here for more details
Upvotes: 2
Reputation: 3343
AnyVal is the root class of all value types, which describe values not implemented as objects in the underlying host system. Value classes are specified in Scala Language Specification, section 12.2. https://www.scala-lang.org/api/current/scala/AnyVal.html
Just like it says, AnyVal
is a root class of value types specified in Scala.
And I assume you are using Java's Integer
. Use Int
instead fixes the issue.
PS It looks like you are trying to create a wrapper class of primitive types, That's where you should use value type using AnyVal
.
Upvotes: 3