8

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?
Mario Galic
  • 47,285
  • 6
  • 56
  • 98
mkUltra
  • 2,828
  • 1
  • 22
  • 47
  • by the way. simplified version doesn't work too : val f = new { def wrapper = new Wrapper("")} – Bogdan Vakulenko Oct 06 '18 at 11:18
  • 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. – Bogdan Vakulenko Oct 06 '18 at 11:26
  • 5
    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. – Owen Oct 06 '18 at 16:37

1 Answers1

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
}
B. D.
  • 11
  • 1
  • 3