gpt4 book ai didi

scala - 编译时检查某些属性

转载 作者:行者123 更新时间:2023-12-01 10:42:08 25 4
gpt4 key购买 nike

给定以下 Scala 代码:

sealed trait Color
case object Red extends Color
case object Blue extends Color

sealed trait Car {
def isBroken: Boolean
def color: Color
}

如何定义这样的方法:

def fixBrokenRedCar(c: A): B

也就是说,AB 应该是什么?该方法应该只接受同时为 RedisBroken = true 的 Car。否则它应该发出一个编译错误。此外,输出 B 应该包含有关其类型的信息,这样如果我创建另一个方法 destroyRedCar(c: B) 并将其应用于输出,它应该相应地进行编译。

最佳答案

然后您应该将数据移动到类型级别:

trait Bool
trait T extends Bool
trait F extends Bool

trait Color
trait Red extends Color
trait Blue extends Color

trait Car[Clr <: Color, Brkn <: Bool]

def fixBrokenCar[Cr <: Car[Red, T]](c: Cr) = new Car[Red, F]{}

scala> fixBrokenCar(new Car[Blue, T]{})
<console>:16: error: inferred type arguments [Car[Blue,T]] do not conform to method fixBrokenCar's type parameter bounds [Cr <: Car[Red,T]]
fixBrokenCar(new Car[Blue, T]{})
^
<console>:16: error: type mismatch;
found : Car[Blue,T]
required: Cr
fixBrokenCar(new Car[Blue, T]{})
^

scala> fixBrokenCar(new Car[Red, T]{})
res3: Car[Red,F] = $anon$1@67d9a642

“摧毁”它:

def destroyRedCar(c: Car[Red, _]) = true

scala> destroyRedCar(fixBrokenCar(new Car[Red, T]{}))
res10: Boolean = true

scala> destroyRedCar(new Car[Red, T]{})
res11: Boolean = true

scala> destroyRedCar(new Car[Blue, T]{})
<console>:15: error: type mismatch;
found : Car[Blue,T]
required: Car[Red, ?]
destroyRedCar(new Car[Blue, T]{})
^

如果需要“变异”Cr类型(从另一种类型构建一种类型,更准确地说):

trait Car[Clr <: Color, Brkn <: Bool] { 
type Copy[C <: Color, B <: Bool] <: Car[C,B] // define "copy" type-method
}

trait BrandedCar[Clr <: Color, Brkn <: Bool] extends Car[Clr, Brkn] {
type Copy[C <: Color, B <: Bool] = BrandedCar[C, B] // implement "copy" type-method
def brand: String = "default"
}

def fixBrokenCar[Cr <: Car[Red, T]](c: Cr) = c.asInstanceOf[Cr#Copy[Red, F]]

def checkBrandedCar(c: BrandedCar[_, F]) = true // accepts only branded and fixed


scala> checkBrandedCar(new BrandedCar[Red, F]{})
res10: Boolean = true

scala> checkBrandedCar(new Car[Red, F]{})
<console>:15: error: type mismatch;
found : Car[Red,F]
required: BrandedCar[?, F]
checkBrandedCar(new Car[Red, F]{})
^

scala> checkBrandedCar(fixBrokenCar(new BrandedCar[Red, T]{}))
res12: Boolean = true

你也可以定义一些def copy[C <: Color, B <: Bool]: Copy[C, B]里面的方法Car的特征(如案例类)而不仅仅是 asInstanceOf .

关于scala - 编译时检查某些属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29469192/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com