Scala types and misunderstanding of inheritance

Could you explain to me what is wrong in this trivial example?

class C1 (val id: Int) 

abstract class C2 [T] {
    def m1 [T] 
}

class C3 [C1] extends C2
{
    override 
    def m1 (obj: C1) {
        println (obj.id)        
    }           
}

I have: value id is not a member of type C1 Why?

+3
source share
2 answers

There are several things in your example. Here is an example modified:

class C1 (val id: Int) 

abstract class C2 [T] {
  // don't repeat [T] and the method takes an arg
  // within C2, T refers to the type parameter
  def m1(t:T) 
}

class C3 extends C2[C1] {  // if in REPL put the brace on the same line
  // no override when implementing abstract 
  def m1(obj:C1) { println(obj.id) } 
}

This should compile (and run in the REPL).

+4
source

By writing class C3[C1], you say that C3 accepts a type parameter C1. Thus, inside the class definition, the class C3name C1refers to this parameter, not the class C1.

What you probably wanted to write was class C3 extends C2[C1](i.e. you pass the class C1 as a type parameter to C2).

+6
source

Source: https://habr.com/ru/post/1765750/


All Articles