小编Lan*_*nak的帖子

Scala:泛型和隐式

我必须开发类 StackMachine[T]。如果 T = Boolean,那么应该有逻辑运算。如果 T = Int,Double,Long 等,应该有算术运算。首先,我开发了类 Stack[T]。

class Stack[T](val stack: List[T]) {
    val length: Int = stack.length
    def isEmpty: Boolean = {length == 0}
    def push(x: T): Stack[T] = {
      new Stack[T](x :: stack)
    }

     def peak: T = {
       if (this.isEmpty)
         throw new ArrayIndexOutOfBoundsException
         else stack.head
     }
    def pop(): Stack[T] = {
      if (this.isEmpty)
        throw new ArrayStoreException()
      val x :: xs = stack
      new Stack[T](xs)
    }
Run Code Online (Sandbox Code Playgroud)

薄的是我不知道如何开发 StackMachine[T] 操作的存在取决于类型。我试过这个:

case class StackMachine[T](val stack:Stack[T]){
    def const(x: T): …
Run Code Online (Sandbox Code Playgroud)

generics scala implicit

2
推荐指数
1
解决办法
61
查看次数

标签 统计

generics ×1

implicit ×1

scala ×1