4

I have a toy class with type member T.

class A { type T = Int }

How can I access my type member. e.g. get the type or modify it.

val a = new A
a.T = String //error: value T is not a member of A

Since T is my member , why I can not access it?

WeiChing 林煒清
  • 4,452
  • 3
  • 30
  • 65

2 Answers2

4

Type members are more like generic parameters than regular class members. Like a generic parameter, you cannot reassign a type parameter or access it from an instance of the class. Read more about type members here, and the difference between abstract types and generic parameters here.

Community
  • 1
  • 1
Ben Reich
  • 16,222
  • 2
  • 38
  • 59
  • In the OP's case it isn't abstract, it's fixed to `Int`. It's just that type members cannot be accessed or reassigned like values. – Michael Zajac Mar 26 '15 at 02:44
3

You can't access it as a value, but you can access it as a type:

scala> class A { type T = Int }
scala> val a = new A
scala> val someInt: a.T = 5
someInt: a.T = 5
abc123
  • 81
  • 2