Reputation: 3321
I am writing insertInOrder
function for a superclass, but cannot access the value age
from the method:
abstract class Parent(age: Int)
case class Child1(age: Int) extends Parent(age)
case class Child2(age: Int) extends Parent(age)
def insertInOrder [U >: Parent] (x: U, acc: List[U] ): List[U] ;
// value age is not a member of type parameter U
I tried this:
def insertInOrder [U >: Parent, U <: Nothing] (x: U, acc: List[U] ): List[U] = {
// U is already defined as type U
What should I do?
Upvotes: 0
Views: 58
Reputation: 9734
In your example age defined in abstract Parent is not accessible, you need to add val in front of it to make accessible from Parent. However you'll have problems with case class overrides for Child. Also you have incorrect type bound for U. That's how I suggest you to fix code:
trait Parent {
def age: Int
}
case class Child1(age: Int) extends Parent
case class Child2(age: Int) extends Parent
def insertInOrder [U <: Parent] (x: U) = {
println(x.age)
}
insertInOrder(Child1(10))
Upvotes: 1
Reputation: 108101
abstract class Parent(val age: Int)
will generate the getter you're looking for.
Upvotes: 1
Reputation: 2938
No getter/setter is created for age constructor parameter in the Parent non-case class. So add 'val' (maybe 'protected val' if it shouldn't be exposed outside of derived classes) to it.
A few examples and a nice summary: https://www.safaribooksonline.com/library/view/scala-cookbook/9781449340292/ch04s03.html
Upvotes: 1