嘗試使用 Scala 3 的元編程功能,我發現行內匹配存在這個問題,我無法通過解釋來滿足自己。
給定一個透明的行內方法eitherTest,該方法接受行內Either[String, Int],然后使用行內匹配運算式直接回傳 theString或 the ,如果輸入 to顯式鍵入 a或 a Int,則一切正常。但是,如果輸入顯式鍵入為. 更讓人好奇的是, 引數本身的型別為。eitherTestLeftRightEithereitherTestEither
這是編譯器錯誤嗎?這是預期的行為嗎?我很難理解為什么編譯器無法解決這個問題。
Scastie 鏈接:https ://scastie.scala-lang.org/CThqajauRVeJvxvW0uYy4w
代碼:
@main def hello: Unit =
workingTest
failingTest
def workingTest: Unit =
val l: Left[String, Int] = Left("hello")
val r: Right[String, Int] = Right(22)
val tl: String = eitherTest(l)
val tr: Int = eitherTest(r)
println(s"$tl :: $tr")
def failingTest: Unit =
val l: Either[String, Int] = Left("hello")
val r: Either[String, Int] = Right(22)
val tl: String = eitherTest(l)
val tr: Int = eitherTest(r)
println(s"$tl :: $tr")
transparent inline def eitherTest(inline v: Either[String, Int]): Any =
inline v match
case Right(a) => a
case Left(b) => b
錯誤:
cannot reduce inline match with
scrutinee: l : (l : Either[String, Int])
patterns : case Right.unapply[String, Int](a @ _):Right[String, Int]
case Left.unapply[String, Int](b @ _):Left[String, Int]
uj5u.com熱心網友回復:
val l: Either[String, Int] = Left("hello")
val r: Either[String, Int] = Right(22)
這會顯式丟棄型別資訊,使編譯器無法推斷出它需要什么。我相信transparent依賴于傳遞引數的型別知識,而不是圍繞靜態定義的值的“暗型別魔法”。如果您洗掉傳遞引數的型別,那么失敗是公平的嗎?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/450958.html
