2016-12-03 87 views
2

我创建了一个名为square的类,扩展了一个称为shape的抽象类。当我在广场上调用getClass时,我得到:class A $ A101 $ A $ A101 $ square而不仅仅是方形。获取自定义Scala对象的类

我想调用getClass(或类似的函数)并获得一个值,该值允许我检查o:Object == square。

任何意见表示赞赏。谢谢

+0

99.9%使用'getClass'是一个可怕的想法。你究竟在做什么? –

+0

@MrD基本上我试图编写一个方法,可以接受任何对象,但应该忽略任何不是指定的一组对象。我是新来的斯卡拉,所以我猜我在回到$ square之前的某种指针?谢谢您的帮助。 –

+0

你应该有你试图过滤某些常见特质或类的子类的类型,然后请求这个共同的特质/类。 –

回答

2

getClass是不是你经常需要的东西。您可以查询具有更好抽象的对象的类型,如isInstanceOfpattern 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 
    | } 
    | } 
+0

谢谢你,那正是我需要的。 –

相关问题