如何在辅助构造函数中调用方法? [英] how can I call a method in auxiliary constructor?

查看:66
本文介绍了如何在辅助构造函数中调用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class foo(val x:Int){
  def convertToInt(z:string) = {do somthing to convert a string to an integer}
  def this(y:string) = this(convertToInt(y))
}

在辅助构造函数(this(y:string))中调用convertToInt会导致这个错误:

calling convertToInt in auxiliary constructor (this(y:string)) causes this error:

error: not found: value convertToInt

我知道我可以使用单例对象并将所有静态函数(如 convertToInt)打包到其中,但这是一个好的解决方案吗?

I know I can use a singleton object and pack all static functions like convertToInt into it, but is it a good solution?

object foo{
    def convertToInt(z:string) = {do somthing to convert a string to an integer}
}   
class foo(val x:Int){
    def this(y:string) = this(foo.convertToInt(y))
}

推荐答案

通过使用angle提供的关于工厂方法而不是辅助构造函数:

by using angle's offer about factory method instead of Auxiliary Constructor:

class Foo(val s:String) {
      val s = ""
      def bar2:String = s+s
      def bar3:List[Char] = s.toList
}

object Foo extends{
      def bar1(y:List[Char]):String =y.mkString
      def apply(s:String)= new Foo(s)
      def apply(y:List[Char])= new Foo(bar1(y))
}

客户端代码:

val foo1 = Foo(List('a','b'))
println(foo1.s)
println(foo1.bar2)
println(foo1.bar3)

这篇关于如何在辅助构造函数中调用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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