Result type in structural refinement may not refer to a user-defined value class
Asked Answered
M

1

9

When I define Wrapper as value class(extending AnyVal):

class Wrapper(val string: String) extends AnyVal

def wrapperHolder(w: Wrapper): {def wrapper: Wrapper} = new {
  def wrapper: Wrapper = w
}

I have following compile error for wrapperHolder:

Error:(5, 22) Result type in structural refinement may not refer to a user-defined value class
def wrapper: Wrapper = w
  • Why it doesn't work for value class?
Manual answered 6/10, 2018 at 10:53 Comment(3)
by the way. simplified version doesn't work too : val f = new { def wrapper = new Wrapper("")}Factual
I assume it's not allowed because value class is not actually a class from java/JVM perspective. it's primitive type with some static helpers generated on compilation stage.Factual
In cases where the value class appears as an argument to a method, it won't work because refinement types often need to call the methods reflectively, and Class.getMethod() has no way to specify a Scala value class. However, this should not be an issue when it only appears as a result type. Perhaps the prohibition has the same origin, though, and Scala prohibits it more broadly than it needs to.Shake
K
0

Declaring a trait may help:

class Wrapper(val string: String) extends AnyVal

trait WrapperHolder {
    def wrapper: Wrapper 
}

def wrapperHolder(w: Wrapper) : WrapperHolder = new WrapperHolder {
    def wrapper: Wrapper = w
}
Kavanagh answered 18/1, 2023 at 19:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.