在scala 3中,如何对iron精炼的类型实现隐式转换?

问题描述 投票:0回答:1

这是我正在尝试做的一个最小的不起作用的示例: 让

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 隐式转换的目标。

感谢您的帮助

scala implicit-conversion iron refinement-type
1个回答
0
投票

回答,您应该使用良好的旧隐式进行内联和类型级编程:

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 
© www.soinside.com 2019 - 2024. All rights reserved.