简体   繁体   中英

Value * is not a member of type parameter Int

package impatient.mapsAndTups.objects


abstract class UnitConversion {
  def convert[T](x: T): T
}

class Inches2Centimeters extends UnitConversion {
  override def convert[Int](x: Int): Int = x * 100
}

object Conversions extends App {
  val c = new Inches2Centimeters()

  println(c.convert(15))
}

I'm not understanding why the preceding code is not compiling. I'm getting the error:

Error:(9, 46) value * is not a member of type parameter Int
  override def convert[Int](x: Int): Int = x * 100

What can I do to fix this?

You have "shadowed" the standard type Int with your own Int within the scope of your method convert . That's because you defined convert to work with a parametric type whose name is Int and which will be defined by callers (and type inference).

One way to fix your code is the following, although I wouldn't do it this way myself.

package impatient.mapsAndTups.objects

abstract class UnitConversion {
  def convert[T](x: T): T
}

class Inches2Centimeters extends UnitConversion {
  def convert[T](x: T): T = x match {
    case t: Int => (t * 100).asInstanceOf[T]
  }
}

object Conversions extends App {
  val c = new Inches2Centimeters()

  println(c.convert(15))
}

Note also that you don't need to override convert in your concrete class.

Instead, I would use the "typeclass" Numeric as follows:

package impatient.mapsAndTups.objects

abstract class UnitConversion {
  def convert[T: Numeric](x: T): T
}

class Inches2Centimeters extends UnitConversion {

  def convert[T: Numeric](x: T): T = {
    val n = implicitly[Numeric[T]]
    n.times(n.fromInt(100), x)
  }
}

object Conversions extends App {
  val c = new Inches2Centimeters()

  println(c.convert(15))
}

I think, what you want is to declare the type parameter at the class level, not function:

abstract class UnitConversion[T] {
  def convert(x: T): T
}

class Inches2Centimeters extends UnitConversion[Int] {
  override def convert(x: Int): Int = x * 100 // this multiplier is wrong :)
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM