这是我正在尝试做的一个最小的不起作用的示例: 让
import io.github.iltotore.iron.*
import io.github.iltotore.iron.constraint.string.*
case class User(name: String)
type Username = String :| StartWith["@"]
def name2user(usern : Username) : User = User(usern)
我想实现隐式转换,以便:
val user : User = "@john" //compile
val user : User = "!john" //not compile
这是我迄今为止尝试过的
given name2user: Conversion[Username, User] = User(_)
val user1 : User = name2user("@john") //
val user2 : User = "@john" //does not compile because "@john" is a String
和
implicit def name2user[S <: String](n: S)(implicit
ev: S <:< Username
): User = User(n)
val user1: User = name2user2("@john") // cannot prove that String <:< Username
val user2: User = "@john" // does not compile because "@john" is a String
这又是一个最小的示例,旨在尽可能简单地说明我集成 Iron 的改进和 Scala 3 隐式转换的目标。
感谢您的帮助
回答,您应该使用良好的旧隐式进行内联和类型级编程:
implicit inline def name2user(inline n: String)
(implicit inline ev: Username = n): User = User(n)
val user3: User = name2user("@john") // compile
val user4: User = "@john" // compile
val user5: User = "#john" // does not compile as it should