classes - CodeProject

Loading...

13,437,477 members (48,021 online)

home

articles

quick answers

Sign in

discussions

features

community

help

Search for articles, questions, tips

Articles » General Reading » Uncategorised Technical Blogs » General

SCALA Properties / classes

Technical Blog View Blog

4.59 (5 votes)

Stats Revisions (4)



Best "Everything Else" Article of October 2015 (Second Prize)

Sacha Barber, 16 Oct 2015

Browse Code



Rate this:

Scala properties/classes

Alternatives Comments (3)

In this post, we will be covering the very basics of how to create properties in our Scala classes, and also talk through how to create simple classes.

Add your own alternative version

Constructors

Tagged as All-Topics

Let’s start by creating a very simple class called “Person ” that will have a single constructor that takes a string for firstname and a string for lastname .

Stats 6.1K views

The firstname and lastname should have getters but no setters.

1 bookmarked

In Scala, this is achieved as follows: Hide Copy Code

Posted 16 Oct 2015

class Person(val firstName: String, val lastName: String) {

CPOL

} Which we may use like this: Hide Copy Code

object ClassesDemo { def main(args: Array[String]) = { val person = new Person("sacha","barber") val theirLastName = person.lastName System.out.print(s"Persons last name is $theirLastName") System.in.read() () } } See how we are using val, this means it is immutable, so we only expose a getter, no setter. If we wanted a getter and a setter, we would instead use var like this: We can also control the access modifiers directly in the constructor as follows: Hide Copy Code

class Person(val firstName: String, private var lastName: String) { } Which now causes a problem is we try and use the lastname field outside of the Person class:

Secondary Constructors As in .NET, it is possible to have multiple constructors. However, the rule in Scala is that any NON primary constructor MUST ALWAYS call the primary constructor. Here is an example using our simple Person class, which has a secondary constructor: Hide Copy Code

///Primary constructor class Person(var firstName: String, var lastName: String) { //secondary constructor def this(firstName: String) { this(firstName, "") } override def toString: String = { return s"firstname: $firstName, lastname: $lastName" } } Which we may use like this: Hide Copy Code

object ClassesDemo { def main(args: Array[String]) = { val person1 = new Person("sacha","barber") val person2 = new Person("ryan") System.out.print(s"Person1 is $person1\r\n") System.out.print(s"Person2 is $person2\r\n") System.in.read() () } } So that talks about how you might write constructors.

Get/Set Another thing we may want to add to our classes (outside of constructors) is properties. Here is our (by now famous) person class, rewritten to include a separate age property. Hide Copy Code

//Primary constructor class Person(var firstName: String, var lastName: String) { // Private age variable, renamed to _age private var _age = 0 var name = "" // Getter def age = _age // Setter def age_= (value:Int):Unit = _age = value override def toString: String = { return s"firstname: $firstName, lastname: $lastName, age: $age" } } Which we can use as follows: Wait a minute, aren’t we meant to be calling a method when we use the age setter? In Scala, parentheses are usually optional. The age setter line could just as easily been written as: Hide Copy Code

person1.age =(99) // OR person1.age_=(99)

Tooling Compatability Scala is a JVM language but is it's not Java, and as such sometimes you may need to do a bit more work if you want to interop with Java correctly. Bean properties may be one area where extra work is required. The reason for this is that in Java Beans, there is an expectation that there are methods call getXXX() and setXXX(). Mmm curious. Luckily in Scala, this is easy to fix, we just need to use a simple BeanProperty annotation. Hide Copy Code

//Primary constructor class Person(var firstName: String, var lastName: String) { @scala.beans.BeanProperty var age = 0 override def toString: String = { return s"firstname: $firstName, lastname: $lastName, age: $age" } } Which you may then use like this: Hide Copy Code

val person1 = new Person("sacha","barber") person1.age = 12 var theirAge = person1.getAge() Note you may also do this on the constructor which may help should you wish to expose constructor parameters as bean properties: Hide Copy Code

class Person( @scala.beans.BeanProperty var firstName: String, @scala.beans.BeanProperty var lastName: String) { }

Methods Methods in Scala are simply defined as follows: Hide Copy Code

def ReverseAString(inputString:String) : String = { return inputString.reverse } Where we specify that it is a method using the def keyword, and then a name for the method, and then any parameters followed by a colon and then a return type, then we supply the method body. We then can call this method like this (assumes we added this method to our Person class) Hide Copy Code

val person1 = new Person("sacha","barber") val reversed = person1.ReverseAString("The cat sat here")

Static Classes / Static Methods This is certainly one area where Scala and .NET differ. In Scala static methods, go into a companion object for the type. I actually think the Scala way makes a lot more sense, when you think about. The Person “OBJECT” has this method. Anyway, here is a small example: Hide Copy Code

//Companion object where Static things live object Person { def StaticDoubleIntMethodOnPersonType(input : Int) : Int = { return input * 2 } } //Primary constructor class Person(var firstName: String, var lastName: String) { override def toString: String = { return s"firstname: $firstName, lastname: $lastName" } } Which you could use like this: Hide Copy Code

val doubled = Person.StaticDoubleIntMethodOnPersonType(10)

License This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share TWITTER

FACEBOOK

About the Author Sacha Barber Software Developer (Senior) United Kingdom I currently hold the following qualifications (amongst others, I also studied Music Technology and Electronics, for my sins) - MSc (Passed with distinctions), in Information Technology for E-Commerce - BSc Hons (1st class) in Computer Science & Artificial Intelligence Both of these at Sussex University UK. Award(s) I am lucky enough to have won a few awards for Zany Crazy code articles over the years Microsoft C# MVP 2016 Codeproject MVP 2016 Microsoft C# MVP 2015 Codeproject MVP 2015 Microsoft C# MVP 2014 Codeproject MVP 2014 Microsoft C# MVP 2013 Codeproject MVP 2013 Microsoft C# MVP 2012 Codeproject MVP 2012 Microsoft C# MVP 2011 Codeproject MVP 2011 Microsoft C# MVP 2010 Codeproject MVP 2010 Microsoft C# MVP 2009 Codeproject MVP 2009 Microsoft C# MVP 2008 Codeproject MVP 2008 And numerous codeproject awards which you can see over at my blog

You may also be interested in... .NET / Scala Interop Using RabbitMQ

Window Tabs (WndTabs) Add-In for DevStudio

10 Differences Between Scala and Java 8: Part 1

Introduction to D3DImage

SAPrefs - Netscape-like Preferences Dialog

Creating alternate GUI using Vector Art

Comments and Discussions

You must Sign In to use this message board.

Search Comments

Spacing Relaxed

Layout Normal

Per page 25

Update

First Prev Next

My vote of 5 Re: My vote of 5

PVX007

23-Nov-15 15:40

Sacha Barber

23-Nov-15 20:10

Last Visit: 31-Dec-99 18:00 Last Update: 12-Mar-18 21:52 General

News

Suggestion

Question

Refresh Bug

Answer

Joke

Praise

Rant

1

Admin

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. Permalink | Advertise | Privacy | Terms of Use | Mobile Web04-2016 | 2.8.180309.2 | Last Updated 17 Oct 2015

Layout: fixed | fluid

Article Copyright 2015 by Sacha Barber Everything else Copyright © CodeProject, 1999-2018

Loading...

classes - CodeProject

13,437,477 members (48,021 online) home articles quick answers Sign in discussions features community help Search for articles, questions, t...

247KB Sizes 3 Downloads 14 Views

Recommend Documents

C# - CodeProject
C# - Free source code and tutorials for Software developers and Architects.; Updated: 9 Dec 2017.

C# - CodeProject
C# - Free source code and tutorials for Software developers and Architects.; Updated: 5 Dec 2017.

ExcelFormat Library - CodeProject
#define XLS_FORMAT_GENERAL L"General" #define XLS_FORMAT_TEXT L"@" #define XLS_FORMAT_INTEGER L"0" #define XLS_FORMAT_DE

MuleSoft Variables Exemplified - CodeProject
Feb 7, 2017 - After setting a flow variable programmers are able to access them through the following "Mule Expression L

Hotel Reservation System - CodeProject
Mar 28, 2009 - An explanation of the useful code within Hotel Reservation System; Author: Jomar Pabuaya; Updated: 30 Mar

C++ Language - CodeProject
C / C++ Language - Free source code and tutorials for Software developers and Architects.; Updated: 7 Dec 2017.

Password hacker - CodeProject
A simple BHO to retrieve the user ID and password.; Author: ram verma; Updated: 17 Sep 2006; Section: ATL; Chapter: Plat

Romeo and Juliet - CodeProject
Dec 3, 2011 - Using the XTree application I recently wrote about, we're going to define the various entities and their r

The Lounge - CodeProject
1 day ago - Technical discussions are encouraged, but click here to ask your programming questions. The Lounge is rated

MFC Discussion Boards - CodeProject
C, Visual C++ and MFC discussions; Updated: 12 Dec 2017.