【发布时间】:2021-10-30 23:07:47
【问题描述】:
我使用来自 scala-newtype 库的值类,但它们看起来与旧的(版本 1.4.0)cats-core 库不兼容。看例子:
import io.estatico.newtype.macros.newtype
import SomeClass.Foo
import cats.syntax.either._
class SomeClass {
def takeFoo(foo: Foo): Unit = {
val strValue: String = foo.value // here I have compile error
println(strValue)
}
}
object SomeClass {
@newtype case class Foo(value: String)
}
object Application extends App {
new SomeClass().takeFoo(Foo("x"))
}
此代码编译时出错:
type mismatch;
found : SomeClass.Foo
(which expands to) SomeClass.Foo.Type
required: String
构建设置:
addCompilerPlugin("org.scalamacros" % "paradise" % "2.1.1" cross CrossVersion.full)
依赖:
scalaVersion := "2.12.10"
libraryDependencies ++= Seq(
"io.estatico" %% "newtype" % "0.4.4",
"org.typelevel" %% "cats-core" % "1.4.0"
)
我发现旧的cats-core 有类EitherIdOpsBinCompat0:
final class EitherIdOpsBinCompat0[A](val value: A) extends AnyVal {
def leftNec[B]: Either[NonEmptyChain[A], B] = Left(NonEmptyChain.one(value))
def rightNec[B]: Either[NonEmptyChain[B], A] = Right(value)
}
具有A 类型的字段value,如果我将strValue 定义替换为:
val strValue: String = catsSyntaxEitherIdBinCompat0(foo).value
我看到同样的错误。
所以,主要问题:为什么编译器看不到值类字段value,而是试图从cats.syntax.either 隐式转换为EitherIdOpsBinCompat0? (见catsSyntaxEitherIdBinCompat0函数)
private[syntax] trait EitherSyntaxBinCompat0 {
implicit final def catsSyntaxEitherBinCompat0[A, B](eab: Either[A, B]): EitherOpsBinCompat0[A, B] =
new EitherOpsBinCompat0(eab)
implicit final def catsSyntaxEitherIdBinCompat0[A](a: A): EitherIdOpsBinCompat0[A] =
new EitherIdOpsBinCompat0(a)
}
我该如何避免这种行为?
PS:
在新的cats-core 版本中,来自EitherIdOpsBinCompat0 的value 字段具有private 修饰符,并且调用值类的value 字段没有问题。
final private[syntax] class EitherIdOpsBinCompat0[A](private val value: A) extends AnyVal { ... }
【问题讨论】:
-
这可能是关于
newtype的问题,而不是关于猫的问题。
标签: scala implicit scala-cats scala-macros