你好Scala的程序员,
我有一个问题或需要保证这是正确的原因,为什么要写一个只能返回值的函数" +"," - "或1,-1。我基本上创建了一个一元函数,它可以返回1或-1用于算术目的和" +"或" - "显示目的取决于传递的参数。这是代码......
package testit
object testit {
abstract class UPairs[T]{
def getFirst():T
def getSecond():T
}
class UString() extends UPairs[String]{
def getFirst():String = "+"
def getSecond():String = "-"
}
object UString {
def apply() = new UString()
}
class UInt() extends UPairs[Int]{
def getFirst():Int = 1
def getSecond():Int = -1
}
object UInt {
def apply() = new UInt()
}
abstract class Unary
case class Positive() extends Unary
case class Negative() extends Unary
def unaryFunc[T](u:Unary, p:UPairs[T]):T = {
u match {
case Positive() => p.getFirst()
case Negative() => p.getSecond()
}
}
def main(args:Array[String]):Unit = {
println(unaryFunc(Positive(), UString()))
println(unaryFunc(Negative(), UInt()))
println(unaryFunc(Positive(), UInt()))
}
}
注意:上述代码有效并产生正确的结果,并将输入限制为有效参数。
答案 0 :(得分:0)
我想我必须采用这种解决方案。
package exprP
object ExprObj {
abstract class UPair[T] {
def getPositive():T
def getNegative():T
}
object UString extends UPair[String] {
def getPositive():String = "+"
def getNegative():String = "-"
}
object UInt extends UPair[Int] {
def getPositive():Int = 1
def getNegative():Int = -1
}
abstract class Unary
case class Positive() extends Unary
case class Negative() extends Unary
def unaryFunc[T](u:Unary, p:UPair[T]):T = {
u match {
case Positive() => p.getPositive()
case Negative() => p.getNegative()
}
}
}