Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Lecture 42: the wide application of generic classes, generic functions and generics in Spark in Scala

Shulou Source: shulou.com Published: 2022-06-02 20:46:15 09月23日 Update

Generics: generally speaking, for example, you need to define a function whose arguments can accept any type. It is not possible to enumerate all parameter type overloading (overload) functions.

Then the program introduces something called generics, which can represent any data type.

For example, List, when creating a List, you can pass in any type, such as × ×, string, floating point number, and so on. That's because List references generics in the class definition.

Definition of List

Sealed abstract class List [+ A] extends AbstractSeq [A] with LinearSeq [A] with Product with GenericTraversableTemplate [A, List] with LinearSeqOptimized [A, list [A]] with Serializable

Where An is the type, of course A you can write any identifier.

Generics are applied to classes and functions. The code example is as follows:

The package com.dt.scala.type_parameterization// generics class class Triple (args: Array [String]) is a type, which is referenced later. Object Hello_type_parameterization {def main (args: Array [String]): Unit = {/ / create an object with the parameter types String, Int, Doubleval triple1 = new Triple ("Spark", 3men3.14) / / visible, defined using generics. You can pass in any type according to your needs when calling. / / you can also specify the type when you create the object val triple2 = new Triple [String,String,String] ("Spark", "Scala", "Kafka") / / new as follows. Then the parameter passed in must be the specified type / / generic function / / define a function that can get the value of the middle position of all kinds of List def getData [T] (l: list [T]) = {l.take (l.length/2)} println (getData (List ("a", "b", "c") println (getData (List (1, 2, 3, 4, 5))})}

Tags: Types functions parameters objects applications popular enumerations things codes representatives positions characters strings that is data methods times identifiers points Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Docker Xiaomi NVidia Linux