在 scala 中使用 case 构造进行类型安全的转换很容易。以下代码确保 square
仅在具有相应类型的对象上调用。
class O
class A extends O {
def square(i: Int):Int = { i*i }
}
class B extends O {
def square(d: Double):Double = { d*d }
}
class C extends O {}
def square(o: O) = o match {
case a:A => print(a.square(3))
case b:B => print(b.square(3.0))
case c:C => print(9)
case _ => print("9")
}
另一方面,在某些情况下,使用类型信息进行转换并仅检查
{def square(Int): Int}
的可用性并不那么容易。就足够了。 scala 中是否有一个构造允许做类似于def square(o: O) = o match {
case a:{def square(Int):Int} => print(a.square(3))
case b:{def square(Double):Double} => print(b.square(3.0))
case _ => print("9")
}
使用隐式证据参数,可以根据其他方法的可用性来定义方法。是否也可以仅在定义时调用它们?
最佳答案
结构类型表示成员的非继承约束可用性,因此如果您希望方法仅接受带有特定方法的值,请说 def square(i: Int): Int
,你使用这个符号:
class Squaring {
type Squarable = { def square(i: Int): Int }
def squareMe(s: Squarable): Int = s.square(17)
}
class CanSquare { def square(i: Int) = i * i }
val cs1 = new CanSquare
val s1 = new Squaring
printf("s1.squareMe(cs1)=%d%n", s1.squareMe(cs1))
s1.squareMe(cs1)=289
您应该知道结构类型是通过反射实现的,但是从 Scala 2.8 开始,反射信息在逐个类的基础上缓存在调用站点(提供值的实际类)。
关于scala - scala 中的类型安全响应是否可能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3434522/