【问题标题】:Is it possible to print the returned value of a function of different class in case of Anonymous object of scala在scala的匿名对象的情况下是否可以打印不同类的函数的返回值
【发布时间】:2017-11-08 21:11:14
【问题描述】:

我是 Scala 的新手,试图了解 Scala 的语法行为。如果有人帮助我,我将不胜感激。谢谢

使用匿名对象: 在这种情况下,如果我想在main 函数体中打印res 的值,那么我需要应用什么逻辑?

package oops

object AnonymousObject 
{
  def main(args:Array[String]):Unit =
  {
    new student().detail(5,9)  // Line 1

  }  
}

class student
{
  def detail(x:Int, y:Int):Int =
  {
    val res = x*y
    println(res)
  }
}

没有匿名对象: 更多信息,在下面给出的这个场景中,实现它没有问题,因为var s

 class Student
 {  
    var id:Int = 0;  // All fields must be initialized  
    var name:String = null;  
 }  
object MainObject
{  
    def main(args:Array[String])
    {  
        var s = new Student()  // Creating an object  
        println(s.id+" "+s.name);  
    }  
}  

【问题讨论】:

  • 在第一种情况下,class student 无法编译。方法detail被注释为返回一个Int,所以它应该只是方法体中的x * y表达式而不是赋值语句。如果要在 main 中打印,请使用 println(new student().detail(5,9))
  • @SamuelHeaney 嗨,谢谢,但不幸的是我尝试了这个println(new student().detail(5,9)),但打印出来的是这个()而不是45
  • 与其做def detail(x: Int, y: Int): Unit = val res = x * y,不如试试def detail(x: Int, y: Int): Int = x * y。当前您正在返回 Unit,它将打印 ()

标签: scala anonymous-objects


【解决方案1】:

一个没有引用名称的对象。所以很简单,你可以在main中这样打印

object AnonymousObject 
{
  def main(args:Array[String]):Unit =
  {
    val res = new student().detail(5,9)
    println(res)

  }  
}

class student
{
  def detail(x:Int, y:Int):Int =
  {
    x*y
  }
}

输出: 45

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    • 2019-07-05
    • 2014-12-12
    相关资源
    最近更新 更多