안녕하세요,
제가 코드를 바꿀 수 없는 패키지에 다음과 같은 클래스 계층이 있어요:
class Outer:
class Inner(number: Int):
???
편하게 쓰려고 Inner를 감싸는 래퍼를 추가하려는데, Inner가 바깥 인스턴스에 의존해서 지금까지는 바깥 클래스의 서브클래스 안에 넣는 방법만 찾았어요:
new Outer:
case class InnerCase(number: Int) extends Inner(number):
???
(new InnerCase(3)).copy() // sample usage
문제는 여러 곳에서 Outer를 상속하면 새 서브클래스마다 편의용 케이스 클래스를 반복해서 넣어야 한다는 거예요. 정의를 계속 복사하지 않도록 임의의 Outer#Inner에 쓸 수 있는 클래스를 만들고 싶어요. 이렇게 시도해 봤어요:
case class InnerCase(number: Int)(owner: Outer) extends owner.Inner(number):
???
new Outer:
host =>
InnerCase(3)(host).copy()(host)
new Outer:
host =>
val instance = InnerCase(4)(host).copy()(host)
val widened: Inner = instance // line causing trouble
그런데 Inner가 필요한 곳에서 InnerCase를 다형적으로 쓰면 이런 진단이 나와요:
Found: InnerCase
Required: Inner
저는 아직 Scala 초보라서, 원하는 걸 이루는 더 나은 방법이 있을 것 같아요. 직접 시도한 방식이 타입 시스템에 어긋나는 데는 타입 이론상의 설명이 있겠죠. 어느 쪽이든 내부 클래스를 상속하는 “올바른” 방법을 알려 주시면 좋겠어요.
영어에서 번역·원문 보기Hi,
In a package whose code is outside my control, there is a hierarchy of classes arranged as follows:
class Outer:
class Inner(number: Int):
???
I'm trying to add a wrapper around Inner as a convenience, but because Inner depends on its enclosing instance, I've only managed to place it within a subclass of that enclosing class:
new Outer:
case class InnerCase(number: Int) extends Inner(number):
???
(new InnerCase(3)).copy() // sample usage
Unfortunately, subclassing Outer in several places means repeating that convenience case class inside each new subclass. To avoid repeatedly duplicating the definition, I'd prefer a class usable with an arbitrary Outer#Inner This is the solution I tried:
case class InnerCase(number: Int)(owner: Outer) extends owner.Inner(number):
???
new Outer:
host =>
InnerCase(3)(host).copy()(host)
new Outer:
host =>
val instance = InnerCase(4)(host).copy()(host)
val widened: Inner = instance // line causing trouble
But using an InnerCase polymorphically in a place requiring an Inner produces this diagnostic:
Found: InnerCase
Required: Inner
I'm still very much a beginner with Scala, so I imagine there must be a better way to achieve what I'm after here. Presumably there's a type-theoretic explanation for why my direct approach violates the type system. Either way, I'd really welcome pointers toward the “proper” approach to subclassing an inner class.