作为scala工厂的伴侣对象
发布时间:2020-12-16 19:25:23 所属栏目:安全 来源:网络整理
导读:我刚刚开始使用 Scala,并开始学习一些教程.我遇到了伴侣对象,并将它们用作工厂.我尝试了几件事.但是,我没有得到以下工作正常.不能让我的头围绕它.. import math._abstract class Point{ // ...}object Point{ private class PointInt(val x:Int,val y:Int) e
我刚刚开始使用
Scala,并开始学习一些教程.我遇到了伴侣对象,并将它们用作工厂.我尝试了几件事.但是,我没有得到以下工作正常.不能让我的头围绕它..
import math._ abstract class Point{ // ... } object Point{ private class PointInt(val x:Int,val y:Int) extends Point{ def +(that:PointInt) = new PointInt(this.x + that.x,this.y + that.y) def distance(that:PointInt) = sqrt(pow((this.x - that.x),2) + pow((this.y - that.y),2)) } private class PointDouble(val x:Double,val y:Double) extends Point{ def +(that:PointDouble) = new PointDouble(this.x + that.x,this.y + that.y) def distance(that:PointDouble) = sqrt(pow((this.x - that.x),2)) } def apply(x:Int,y:Int):Point = new PointInt(x,y) def apply(x:Double,y:Double):Point = new PointDouble(x,y) } val a = Point(1,2) val b = Point(3,4) val c = a+b // does not work... 只是试图加起来两个整数点,就像我在方法中定义的那样……有谁知道我做错了什么? 编辑:我当时试图在工厂中包装以下(工作)类. class Point(val x:Int,val y:Int){ def +(that:Point) = new Point(this.x + that.x,this.y + that.y) def distance(that:Point) = sqrt(pow((this.x - that.x),2)) } val a = new Point(1,2) //> a : week1.OU2.Point = week1.OU2$Point@73e48fa7 val b = new Point(3,4) //> b : week1.OU2.Point = week1.OU2$Point@677bb8fe val c = a+b //> c : week1.OU2.Point = week1.OU2$Point@6bae60c5 c.x //> res0: Int = 4 c.y //> res1: Int = 6 解决方法
我不太确定哪些约束实际上强加给你,例如,哪些类应该/必须是私有的,但使用F-bounded多态可能是你想要的解决方案的垫脚石.
/* Simplified interface (adding sqrt is straight-forward) */ abstract class Point[P <: Point[P]] { def +(that: P): P } /* Two implementations */ class PointInt(val x:Int,val y:Int) extends Point[PointInt] { def +(that:PointInt) = new PointInt(this.x + that.x,this.y + that.y) } class PointDouble(val x:Double,val y:Double) extends Point[PointDouble] { def +(that:PointDouble) = new PointDouble(this.x + that.x,this.y + that.y) } /* Companion object */ object Point { def apply(x:Int,y:Int) = new PointInt(x,y:Double) = new PointDouble(x,y) } /* Use cases */ val a = Point(1,4) val c = a+b // ok val d = Point(1.0,2.5) val e = c+d // error: type mismatch 但请注意,如果您想要隐藏您的实现,这将无法帮助您,即,将它们设为私有并仅使用通用Point声明公共接口 – 正如其他人已经指出的那样. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |