2
我创建了一个名为square的类,扩展了一个称为shape的抽象类。当我在广场上调用getClass时,我得到:class A $ A101 $ A $ A101 $ square而不仅仅是方形。获取自定义Scala对象的类
我想调用getClass(或类似的函数)并获得一个值,该值允许我检查o:Object == square。
任何意见表示赞赏。谢谢
我创建了一个名为square的类,扩展了一个称为shape的抽象类。当我在广场上调用getClass时,我得到:class A $ A101 $ A $ A101 $ square而不仅仅是方形。获取自定义Scala对象的类
我想调用getClass(或类似的函数)并获得一个值,该值允许我检查o:Object == square。
任何意见表示赞赏。谢谢
getClass
是不是你经常需要的东西。您可以查询具有更好抽象的对象的类型,如isInstanceOf
或pattern matching。
下面是一些REPL:
scala> abstract class Shape
defined class Shape
scala> class Square extends Shape
defined class Square
scala> class Circle extends Shape
defined class Circle
scala> def isSquare(s: Shape): Boolean = s.isInstanceOf[Square]
isSquare: (s: Shape)Boolean
scala> isSquare(new Circle)
res4: Boolean = false
scala> isSquare(new Square)
res5: Boolean = true
下面就来写isSquare
的另一种方法:时间
scala> def isSquare(s: Shape): Boolean = {
| s match {
| case sq: Square => true
| case _ => false
| }
| }
谢谢你,那正是我需要的。 –
99.9%使用'getClass'是一个可怕的想法。你究竟在做什么? –
@MrD基本上我试图编写一个方法,可以接受任何对象,但应该忽略任何不是指定的一组对象。我是新来的斯卡拉,所以我猜我在回到$ square之前的某种指针?谢谢您的帮助。 –
你应该有你试图过滤某些常见特质或类的子类的类型,然后请求这个共同的特质/类。 –