Inherited type alias in Scala is invisible in constructor declaration but visible in constructor body

StackOverflow https://stackoverflow.com/questions/22407797

  •  14-06-2023
  •  | 
  •  

Question

Why does Scala behave like this ?

More importantly, how can this code be fixed ?

I am asking this question because I have complicated types that I need to use in constructor declarations in several subclasses and I want to stay DRY.

class Parent{
  type IntAlias=Int
}

class Child (val i1:IntAlias=3) extends Parent{ //Compilation error, why ?
  val i2:IntAlias= 1  //No problem here!
}

Compiler error:

 not found: type IntAlias
class Child (val i1:IntAlias=3) extends Parent{
                    ^
Était-ce utile?

La solution

In your definition, IntAlias is a member of class Parent. So without an instance of Parent you cannot access that member. You can read your second case as val i2: this.IntAlias = 1. Here you have access to the instance this.

This is similar to the following for values instead of types:

class Parent {
  def intValue: Int = 1234
}

class Child(val x: Int = intValue) extends Parent  // does not compile

So you must put that member in a different scope, for example a companion object:

 object Parent {
   type IntAlias = Int
 }
 import Parent.IntAlias

 class Child(val i1: IntAlias = 3) extends Parent {
   val i2: IntAlias = 1
 }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top