带有Scala富包装的类的新构造函数(隐式) [英] New constructors for classes with Scala rich wrapping (implicit)

查看:637
本文介绍了带有Scala富包装的类的新构造函数(隐式)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Scala中,您可以通过创建包装类并使用implicit def将原始类转换为丰富的包装类来添加新方法到现有类。



我有一个java库的图形,使用大量的构造函数与浮动列表。我想要添加新的构造函数到这些类与丰富的包装,但这似乎不像上面的方法工作。换句话说,我想有更简单的构造函数,但仍然能够保持使用原始的类名,而不是一些包装类名,但目前我没有看到其他选项。



想法?

解决方案听起来像你想使用Scala的apply(...)工厂方法,


$ b

$ c> class Foo(val bar:Int,val baz:Int){
... class definition ...
}

您可以在同一文件中添加:

  object Foo { 
def apply(bar:Int)= new Foo(bar,0)
}

现在,创建一个新的Foo实例,只提供bar参数,就像

  val myBar = 42 
val myFoo = Foo(myBar)//注意缺少'new'关键字。

这将导致myFoo被分配一个Foo的实例,其中bar = 42,baz = 0。


In Scala, you can "add new methods" to existing classes by creating wrapper class and using "implicit def" to convert from the original class to the rich wrapper class.

I have a java library for graphics that uses plenty of constructors with looong lists of floats. I would love to add new constructors to these classes with rich wrapping but this doens't seem to work like the above for methods. In other words, I would like to have simpler constructors but still to be able to keep using the original class names and not some wrapper class names but currently I see no other options.

Ideas?

解决方案

Sounds like you want to use Scala's apply(...) factory methods, which you build in to the companion object for your class.

For example, if you have:

class Foo(val bar: Int, val baz: Int) {
  ... class definition ...
}

You could add (in the same file):

object Foo {
  def apply(bar: Int) = new Foo(bar, 0)
}

With this in hand, creating a new Foo instance, just providing the bar parameter, is as easy as

val myBar = 42
val myFoo = Foo(myBar) // Note the lack of the 'new' keyword.

This will result in myFoo being assigned an instance of Foo where bar = 42, and baz = 0.

这篇关于带有Scala富包装的类的新构造函数(隐式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆