1

I thought I had a good understanding of the proper use of the type keyword in Scala, from reading these articles:

Understanding what 'type' keyword does in Scala
Scala: Abstract types vs generics

However, I'm not clear as to why the following code will not compile. With AddableNum being defined as it is, I should be able define add() for anything that defines addition between two integers, yes? Ah, but no! What am I missing?

type Nums <:Int
type AddableNum <: { def +(x:Nums): Nums}
class MyNum (value:AddableNum) {
    def add (that:Nums) : Nums = value + that
}
val i:Int = 5
val test = new MyNum(i)  // DOES NOT COMPILE
Community
  • 1
  • 1
ab1000000
  • 19
  • 3

1 Answers1

1

Few issues in your code, try to use code below:

type Nums = Int // should use '=', because AddableNum can't refer to abstract type 

// AddableNum is a type alias for structural type definition
// should use AnyVal for accept Int (by default AnyRef) 
type AddableNum = AnyVal { def +(x:Nums): Nums} 

class MyNum[T <: AddableNum](value: T) { // use type constraints here (instead line above)
  def add (that:Nums) : Nums = value + that
}

val i:Int = 5
val test = new MyNum(i)  // COMPILE
Yuriy
  • 2,772
  • 15
  • 22