extends,with关键字的区别

package withextends.diff

/**
  * Created by jack on 2017/8/1.
  */
trait Abstract {

  type T

  def gett(x: T): T

  def init: T
}

abstract class A {
  val v: String

  def m: String
}
//
class ab extends A with Abstract{
  override val v: String = _

  override def m: String = "method"

  override type T = String

  override def gett(x: String): String = {
    this.m
  }

  override def init: String = "init"
}

class wes {

}
object Test extends App {
  val x = new ab
  val y = new wes with Abstract {
    override type T = this.type

    override def gett(x: this.type): this.type = ???

    override def init: this.type = ???
  }
  //compile error
  /*val z = new wes extends A {

  }*/
  type y = ab with A
  //compile error
  /*type z = ab extens A*/
}
总结一下extends和with的区别:
1、无论是继承abstract class或者混入trait,对于一个要实现的类来说,必须先用extends,剩下的用with,否则编译的时候就会出错
当同时实现abstract class和trait的时候,abstract class必须在前,而trait必须在后,如果仅实现其一的话,只可以用extends
2、当直接new一个实现了trait的对象的时候的时候是可以使用with关键字的
3、T with U可以是一个新的type,但是T extends U并不是一个新的类型
 
 

                
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值