csdn_lss
2018-05-03 14:54
采纳率: 50%
浏览 709

scala自定义隐式转换失败,求指导啊!

//1.失败不能隐式转换。no implicit ordering defined from Girl
implicit def girl2Ordering(g: Girl) = new Ordering[Girl] {
    override def compare(x: Girl, y: Girl) = {
        x.faceValue-y.faceValue
   }
}

//2.能够运行成功。
implicit val girl2Ordering = new Ordering[Girl] {
    override def compare(x: Girl, y: Girl): Int = {
        x.faceValue - y.faceValue
   }
}
class Chooser[T: Ordering] {

  def choose(first: T, second: T): T = {
    //implicit 隐式参数
    val ord = implicitly[Ordering[T]]
    if (ord.gt(first, second)) first else second

  }
}

object Chooser {
  def main(args: Array[String]): Unit = {
    import MyPredef._
    val c = new Chooser[Girl]
    val a = new Girl("a", 90)
    val b = new Girl("b", 88)
    val girl = c.choose(a, b)
    println(girl.name)
  }
}

请问为什么1会失败?还望指教!

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • csdn_lss 2018-05-03 16:04

    每次发完帖子以后就突然想通了. -_-

        implicit def girl2Ordering = new Ordering[Girl] {
          override def compare(x: Girl, y: Girl) = {
            x.faceValue - y.faceValue
          }
        }
        ``` 
    
    打赏 评论
  • csdn_lss 2018-05-03 16:06
      implicit val girl2Ordering = () => new Ordering[Girl] {
        override def compare(x: Girl, y: Girl): Int = {
          x.faceValue - y.faceValue
        }
      }
    
    
      implicit val girl2Ordering =  new Ordering[Girl] {
        override def compare(x: Girl, y: Girl): Int = {
          x.faceValue - y.faceValue
        }
      }
    
    打赏 评论

相关推荐 更多相似问题