bug icon indicating copy to clipboard operation
bug copied to clipboard

Can't define value class's value as implicit

Open scabug opened this issue 9 years ago • 2 comments

Seems you can't define a value class's value as implicit:

class IntW(implicit val n: Int) extends AnyVal

Foo.scala:1: error: value class may not be a member of another class
class Foo(implicit val n: Int) extends AnyVal
      ^
one error found

The use of Int here as an implicit class is just for reproduction purpose, it wouldn't be wise to do so.

The current workaround is to drop the implicit and define an implicit method:

class IntW(val n: Int) extends AnyVal {
  private implicit def implicitInt: Int = n 
}

scabug avatar Dec 21 '15 17:12 scabug

Imported From: https://issues.scala-lang.org/browse/SI-9601?orig=1 Reporter: @dwijnand Affected Versions: 2.11.7

scabug avatar Dec 21 '15 17:12 scabug

The error is now

scala> class IntW(implicit val n: Int) extends AnyVal
<console>:11: error: value class needs to have exactly one val parameter
       class IntW(implicit val n: Int) extends AnyVal
             ^

hrhino avatar Dec 07 '17 20:12 hrhino