简体   繁体   English

Scala案例类接受什么输入?

[英]what input do scala case classes accept?

The code below seems to work fine. 下面的代码似乎工作正常。 But my question is that why the function is defined to take Strings as input but on the bottom, it has accepted some input integers? 但是我的问题是,为什么函数定义为将Strings作为输入,但在底部却接受了一些输入整数?

case class 案例类

TempData(year:Int, month:String, Prec:Double, Maxtemp:Int, Meantemp:Int, Mintemp:Int)
    def parseLine(line:String):TempData = {
        val p = line.split(",")
        TempData(p(1).toInt, p(3).toString, p(5).toDouble, p(6).toInt, p(8).toInt, p(10).toInt)
    }

    //> parseLine: (line: String)Tests.TempData
    parseLine("Verizon, 2017, Alpha, October, gentlemen, 10.3, 5, Dallas, 67, schools, 42")
    //> res0: Tests.TempData = TempData(2017, October, 10.3, 5, 67, 42)

Your function takes one single String as an argument.. 您的函数将一个String用作参数。

def parseLine(line: String): TempData

And one single String is exactly what is passed to it: 一个String正是传递给它的:

scala> "Verizon,2017,Alpha,October,gentlemen,10.3,5,Dallas,67,schools,42"
res0: String = Verizon,2017,Alpha,October,gentlemen,10.3,5,Dallas,67,schools,42

The numbers are just plain text and are a part of that String , there are no integers involved. 数字只是纯文本,是String的一部分,不涉及整数。 It's the body of your function that splits the String and extracts Int s from it. 函数的主体将String拆分并从中提取Int

edit: regarding the title of your post: all of that has nothing to do with your TempData case class. 编辑:关于您的帖子的标题:所有这些与您的TempData案例类无关。 It seems that you are confusing the call of the case class constructor with the call to parseLine . 似乎您将case类构造函数的调用与parseLine的调用parseLine

The defined function parseLine(line: String) takes String type arguments, and you have passed it correctly. 定义的函数parseLine(line: String)接受String类型的参数,并且您已正确传递了它。 The confusion is that you are considering the numbers present in the string as integers(Int) which is incorrect. 混乱之处在于您正在考虑将字符串中存在的数字视为integers(Int),这是不正确的。 The numbers present in the string are of type String only because you have enclosed them in quotes. 目前在字符串中的数字是类型的String只是因为你已经在引号它们。 You can also reason out for using toInt for converting the the numbers from String to Int type. 您还可以toInt出使用toInt将数字从String转换为Int类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM